Skip to content

Commit

Permalink
Batch SQL queries where possible
Browse files Browse the repository at this point in the history
  • Loading branch information
Shinsina committed Aug 8, 2024
1 parent 222952f commit 37e3b5d
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 80 deletions.
26 changes: 14 additions & 12 deletions src/pages/shared-subsessions.astro
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,19 @@ const sharedRaceSessions = await db
)
.having(({ count }) => gt(count, 1));
const sharedSubsessionIds = sharedRaceSessions.map((v) => v.subsession_id);
const sharedSubsessions = await db
.select()
.from(Subsession)
.where(sql`${Subsession.subsession_id} IN ${sharedSubsessionIds}`)
.orderBy(desc(Subsession.subsession_id));
const sharedSubsessionRaceResults = await db
.select()
.from(SubsessionRaceResults)
.where(
sql`${SubsessionRaceResults.cust_id} IN ${userIds} AND ${SubsessionRaceResults.simsession_number} = 0 AND ${SubsessionRaceResults.subsession_id} IN ${sharedSubsessionIds}`
);
const [sharedSubsessions, sharedSubsessionRaceResults] = await db.batch([
db
.select()
.from(Subsession)
.where(sql`${Subsession.subsession_id} IN ${sharedSubsessionIds}`)
.orderBy(desc(Subsession.subsession_id)),
db
.select()
.from(SubsessionRaceResults)
.where(
sql`${SubsessionRaceResults.cust_id} IN ${userIds} AND ${SubsessionRaceResults.simsession_number} = 0 AND ${SubsessionRaceResults.subsession_id} IN ${sharedSubsessionIds}`
),
]);
const subsessionIdToSharedRaceResultsMap = sharedSubsessionRaceResults.reduce(
(map: Map<number, Array<typeof value>>, value) => {
const { subsession_id } = value;
Expand Down Expand Up @@ -93,7 +95,7 @@ const results = sharedSubsessions.map((subsession) => {
headToHeadWins[display_name] = [subsession_id];
}
const { group_name: License } = Array.isArray(allowed_licenses)
? allowed_licenses.slice(0, 2).pop() as LicenseType
? (allowed_licenses.slice(0, 2).pop() as LicenseType)
: { group_name: "" };
const assertTrackAsTrackType = () => track as Track;
const trackInfo = assertTrackAsTrackType();
Expand Down
43 changes: 23 additions & 20 deletions src/pages/subsession/[id].astro
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,28 @@ export async function getStaticPaths() {
return subsessions.map(({ subsession_id: id }) => ({ params: { id } }));
}
const { id } = Astro.params;
const [subsession] = await db
.select()
.from(Subsession)
.where(eq(Subsession.subsession_id, Number(id)));
const practiceResults = await db
.select()
.from(SubsessionPracticeResults)
.where(eq(SubsessionPracticeResults.subsession_id, Number(id)))
.orderBy(asc(SubsessionPracticeResults.finish_position));
const qualifyingResults = await db
.select()
.from(SubsessionQualifyingResults)
.where(eq(SubsessionQualifyingResults.subsession_id, Number(id)))
.orderBy(asc(SubsessionQualifyingResults.finish_position));
const raceResults = await db
.select()
.from(SubsessionRaceResults)
.where(eq(SubsessionRaceResults.subsession_id, Number(id)))
.orderBy(asc(SubsessionRaceResults.finish_position));
const [subsessions, practiceResults, qualifyingResults, raceResults] = await db.batch([
db
.select()
.from(Subsession)
.where(eq(Subsession.subsession_id, Number(id))),
db
.select()
.from(SubsessionPracticeResults)
.where(eq(SubsessionPracticeResults.subsession_id, Number(id)))
.orderBy(asc(SubsessionPracticeResults.finish_position)),
db
.select()
.from(SubsessionQualifyingResults)
.where(eq(SubsessionQualifyingResults.subsession_id, Number(id)))
.orderBy(asc(SubsessionQualifyingResults.finish_position)),
db
.select()
.from(SubsessionRaceResults)
.where(eq(SubsessionRaceResults.subsession_id, Number(id)))
.orderBy(asc(SubsessionRaceResults.finish_position)),
]);
const subsession = subsessions.pop();
const [practiceResultOne] = practiceResults || [{}];
const [qualifyingResultOne] = qualifyingResults || [{}];
const splitRaceResults = raceResults.find((result) =>
Expand Down Expand Up @@ -108,7 +111,7 @@ const {
const title = `Subsession - ${id}`;
const description = `Subsession information for subsession - ${id}`;
const notMultiClass =
Array.isArray(subsession.car_classes) && subsession.car_classes.length === 1;
Array.isArray(subsession?.car_classes) && subsession?.car_classes.length === 1;
---

<DefaultLayout {title} {description}>
Expand Down
27 changes: 15 additions & 12 deletions src/pages/user/[id]/scheduling/by-week/[timestamp].astro
Original file line number Diff line number Diff line change
Expand Up @@ -19,40 +19,44 @@ export async function getStaticPaths() {
.flat();
}
const { id, timestamp } = Astro.params;
const [user] = await db
const [users, cars, carClassesResults, carClasses, seasons] = await db.batch([
db
.select({
carPackages: User.car_packages,
trackPackages: User.track_packages,
})
.from(User)
.where(eq(User.cust_id, id));
.where(eq(User.cust_id, id)),
db.select().from(Car),
db
.select({
carClassId: CarClass.car_class_id,
carsInClass: CarClass.cars_in_class,
})
.from(CarClass),
db.select().from(CarClass),
db.select().from(Season)
]);
const user = users.pop() || { carPackages: [], trackPackages: [] };
const { carPackages, trackPackages } = user;
const carIds = Array.isArray(carPackages)
? carPackages.map((carPackage) => carPackage.content_ids).flat()
: [];
const trackIds = Array.isArray(trackPackages)
? trackPackages.map((trackPackage) => trackPackage.content_ids).flat()
: [];
const cars = await db.select().from(Car);
const carsMap = new Map();
cars.forEach((car) => {
const { car_id } = car;
carsMap.set(car_id, car);
});
// @todo Improve this query to not have to do this
const carClassesResults = await db
.select({
carClassId: CarClass.car_class_id,
carsInClass: CarClass.cars_in_class,
})
.from(CarClass);
// @todo Improve CarClass query to not have to do this
const carClassIdsForCarIds = carClassesResults
.filter((result: any) =>
result.carsInClass.some((v: any) => carIds.includes(v.car_id))
)
.map((result) => result.carClassId);
// End comment of previous todo
const carClasses = await db.select().from(CarClass);
const carClassesMap = new Map();
carClasses.forEach((carClass) => {
const { car_class_id, cars_in_class } = carClass;
Expand All @@ -70,7 +74,6 @@ const licenseGroupToNameMap: Record<string, string> = {
"4": "Class B",
"5": "Class A",
};
const seasons = await db.select().from(Season);
const schedulesForWeek = seasons.reduce(
(array: Array<Record<string, unknown>>, season) => {
const { schedules, ...rest } = season;
Expand Down
27 changes: 15 additions & 12 deletions src/pages/user/[id]/scheduling/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,44 @@ export async function getStaticPaths() {
return userIds.map(({ id }) => ({ params: { id } }));
}
const { id } = Astro.params;
const [user] = await db
const [users, cars, carClassesResults, carClasses, seasons] = await db.batch([
db
.select({
carPackages: User.car_packages,
trackPackages: User.track_packages,
})
.from(User)
.where(eq(User.cust_id, id));
.where(eq(User.cust_id, id)),
db.select().from(Car),
db
.select({
carClassId: CarClass.car_class_id,
carsInClass: CarClass.cars_in_class,
})
.from(CarClass),
db.select().from(CarClass),
db.select().from(Season)
]);
const user = users.pop() || { carPackages: [], trackPackages: [] };
const { carPackages, trackPackages } = user;
const carIds = Array.isArray(carPackages)
? carPackages.map((carPackage) => carPackage.content_ids).flat()
: [];
const trackIds = Array.isArray(trackPackages)
? trackPackages.map((trackPackage) => trackPackage.content_ids).flat()
: [];
const cars = await db.select().from(Car);
const carsMap = new Map();
cars.forEach((car) => {
const { car_id } = car;
carsMap.set(car_id, car);
});
// @todo Improve this query to not have to do this
const carClassesResults = await db
.select({
carClassId: CarClass.car_class_id,
carsInClass: CarClass.cars_in_class,
})
.from(CarClass);
// @todo Improve CarClass query to not have to do this
const carClassIdsForCarIds = carClassesResults
.filter((result: any) =>
result.carsInClass.some((v: any) => carIds.includes(v.car_id))
)
.map((result) => result.carClassId);
// End comment of previous todo
const carClasses = await db.select().from(CarClass);
const carClassesMap = new Map();
carClasses.forEach((carClass) => {
const { car_class_id, cars_in_class } = carClass;
Expand All @@ -49,7 +53,6 @@ carClasses.forEach((carClass) => {
: [];
carClassesMap.set(car_class_id, { ...carClass, cars_in_class: carsInClass });
});
const seasons = await db.select().from(Season);
const carClassIdSet = new Set(carClassIdsForCarIds);
const trackIdSet = new Set(trackIds);
const licenseGroupToNameMap: Record<string, string> = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,31 +35,43 @@ export async function getStaticPaths() {
}));
}
const { id, seasonId, carClassId } = Astro.params;
const allSeasonSubsessions = await db
.select()
.from(Subsession)
.innerJoin(
SubsessionRaceResults,
eq(Subsession.subsession_id, SubsessionRaceResults.subsession_id)
)
.where(
and(
eq(Subsession.season_id, Number(seasonId)),
eq(SubsessionRaceResults.cust_id, Number(id)),
eq(SubsessionRaceResults.car_class_id, Number(carClassId)),
sql`${SubsessionRaceResults.simsession_name} IN ${["RACE", "FEATURE", "N/A"]}`
const [subsessions, seasons, pastSeasonInformations] = await db.batch([
db
.select()
.from(Subsession)
.innerJoin(
SubsessionRaceResults,
eq(Subsession.subsession_id, SubsessionRaceResults.subsession_id)
)
);
const subsessions = allSeasonSubsessions;
const [season] = await db
.select()
.from(Standing)
.where(eq(Standing.id, `${seasonId}_${carClassId}_${id}`));
const [pastSeasonInformation] = await db
.select()
.from(PastSeason)
.where(eq(PastSeason.season_id, Number(seasonId)));
const trackSchedule = Array.isArray(pastSeasonInformation.race_weeks)
.where(
and(
eq(Subsession.season_id, Number(seasonId)),
eq(SubsessionRaceResults.cust_id, Number(id)),
eq(SubsessionRaceResults.car_class_id, Number(carClassId)),
sql`${SubsessionRaceResults.simsession_name} IN ${["RACE", "FEATURE", "N/A"]}`
)
),
db
.select()
.from(Standing)
.where(eq(Standing.id, `${seasonId}_${carClassId}_${id}`)),
db
.select()
.from(PastSeason)
.where(eq(PastSeason.season_id, Number(seasonId))),
]);
const season = seasons.pop() || {
division: 0,
division_rank: 0,
overall_rank: 0,
season_name: "",
display_name: "",
points: 0,
};
const pastSeasonInformation = pastSeasonInformations.pop() || {
race_weeks: [],
};
const trackSchedule = Array.isArray(pastSeasonInformation?.race_weeks)
? pastSeasonInformation.race_weeks.map((raceWeek: Record<string, Track>) => ({
...raceWeek.track,
race_week_num: raceWeek.race_week_num,
Expand Down

0 comments on commit 37e3b5d

Please sign in to comment.