36IKBCJKMV6NPBP2TYPZFE7IY22K33VTKETTFYLB7AN2Y7TI6ZAQC
// First, query species_dataset junction table to get species IDs for this dataset
const speciesIdsResult = await db
// Use JOIN approach to get species and call types in a single query
// This eliminates the N+1 query problem and reduces round trips to the database
const queryResults = await db
.from(speciesDataset)
.where(eq(speciesDataset.datasetId, datasetId));
.from(species)
.innerJoin(
speciesDataset,
eq(species.id, speciesDataset.speciesId)
)
.leftJoin(
callType,
sqlExpr`${callType.speciesId} = ${species.id} AND ${callType.active} = true`
)
.where(eq(speciesDataset.datasetId, datasetId))
.orderBy(species.label);
// Extract the species IDs
const speciesIds = speciesIdsResult.map(result => result.speciesId);
const speciesIdsQuoted = speciesIds.map(id => `'${id}'`).join(',');
// Transform the flat results into nested objects
// Using a Map for better performance with large datasets
const speciesMap = new Map();
// Get the species details
const speciesResults = await db
.select({
id: species.id,
label: species.label,
ebirdCode: species.ebirdCode,
description: species.description
})
.from(species)
.where(sqlExpr`${species.id} IN (${sqlExpr.raw(speciesIdsQuoted)})`);
// Get call types for all these species
const callTypesResults = await db
.select({
speciesId: callType.speciesId,
id: callType.id,
label: callType.label
})
.from(callType)
.where(sqlExpr`${callType.speciesId} IN (${sqlExpr.raw(speciesIdsQuoted)}) AND ${callType.active} = true`);
// Group call types by species ID for easier mapping
const callTypesBySpecies: Record<string, { id: string, label: string }[]> = {};
callTypesResults.forEach(callTypeItem => {
if (!callTypesBySpecies[callTypeItem.speciesId]) {
callTypesBySpecies[callTypeItem.speciesId] = [];
queryResults.forEach(row => {
if (!speciesMap.has(row.id)) {
// Create a new species entry if not already in the map
speciesMap.set(row.id, {
id: row.id,
label: row.label,
ebirdCode: row.ebirdCode,
description: row.description,
callTypes: []
});
callTypesBySpecies[callTypeItem.speciesId].push({
id: callTypeItem.id,
label: callTypeItem.label
});
// Add the call type if it exists and isn't already in the array
if (row.callTypeId) {
const species = speciesMap.get(row.id);
const existingCallType = species.callTypes.find((ct: { id: string }) => ct.id === row.callTypeId);
if (!existingCallType) {
species.callTypes.push({
id: row.callTypeId,
label: row.callTypeLabel
});
}
}
// Combine species with their call types
const enrichedSpecies = speciesResults.map(speciesItem => ({
id: speciesItem.id,
label: speciesItem.label,
ebirdCode: speciesItem.ebirdCode,
description: speciesItem.description,
callTypes: callTypesBySpecies[speciesItem.id] || []
}));
// Convert map to array
const enrichedSpecies = Array.from(speciesMap.values());