Making CTE's reusable

I wanted to make certain cte's in my project reusable and came up with the following solution.

Is there a "kysely" way to do this?

export const getPiggyBank = async (teacherID: number) => {
  const lessons = await db
    .with("get_attendances", () => Attendance.byTeacherID(teacherID))
    .selectFrom("lesson")
    .innerJoin("get_attendances", "lesson.ID", "get_attendances.lessonID")
    .select((eb) => [
      "lesson.ID",
      "lesson.date",
      "lesson.index",
      jsonArrayFrom(
        eb
          .selectFrom("get_attendances as a")
          .select([
            "a.ID",
            "a.function",
            "a.hours",
            "a.paymentType",
            "a.hourlyWage",
          ])
          .whereRef("a.lessonID", "=", "lesson.ID")
      ).as("attendances"),
    ])
    .where("lesson.isActive", "=", true)
    .groupBy(["lesson.ID", "lesson.date", "lesson.index"])
    .execute();

  return lessons;
};

// CTE's

export const Attendance = {
  byTeacherID: (teacherID: number) =>
    db
      .selectFrom("attendance")
      .innerJoin("function", "attendance.functionID", "function.ID")
      .innerJoin("group", "attendance.groupID", "group.ID")
      .select([
        "attendance.ID",
        "attendance.lessonID",
        "group.hours",
        "group.paymentType",
        "function.name as function",
        "function.hourlyWage",
      ])
      .where("attendance.teacherID", "=", teacherID)
      .where("attendance.attendanceType", "=", ATTENDANCETYPES.PRESENT)
      .where("attendance.isActive", "=", true),
};
Solution
Hey 👋

There isn't a "kysely way" to do this.
Was this page helpful?