36IKBCJKMV6NPBP2TYPZFE7IY22K33VTKETTFYLB7AN2Y7TI6ZAQC // First, query species_dataset junction table to get species IDs for this datasetconst 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 databaseconst 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 IDsconst 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 datasetsconst speciesMap = new Map();
// Get the species detailsconst 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 speciesconst 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 mappingconst 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 mapspeciesMap.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 arrayif (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 typesconst enrichedSpecies = speciesResults.map(speciesItem => ({id: speciesItem.id,label: speciesItem.label,ebirdCode: speciesItem.ebirdCode,description: speciesItem.description,callTypes: callTypesBySpecies[speciesItem.id] || []}));
// Convert map to arrayconst enrichedSpecies = Array.from(speciesMap.values());