···437437438438 // Optimized query for collections: use incremental aggregation with window functions
439439 const collectionsQuery = sql`
440440- WITH period_collection_counts AS (
440440+ WITH all_collections AS (
441441+ SELECT
442442+ access_type,
443443+ created_at
444444+ FROM ${collections}
445445+ WHERE created_at IS NOT NULL
446446+ ),
447447+ all_periods AS (
448448+ SELECT DISTINCT date_trunc(${interval}, created_at) AS period
449449+ FROM all_collections
450450+ ),
451451+ all_access_types AS (
452452+ SELECT DISTINCT access_type
453453+ FROM all_collections
454454+ ),
455455+ period_type_grid AS (
456456+ SELECT p.period, t.access_type
457457+ FROM all_periods p
458458+ CROSS JOIN all_access_types t
459459+ ),
460460+ period_counts AS (
441461 SELECT
442462 date_trunc(${interval}, created_at) AS period,
443463 access_type,
444464 COUNT(*)::int AS period_count
445445- FROM ${collections}
446446- WHERE created_at IS NOT NULL
465465+ FROM all_collections
447466 GROUP BY 1, 2
467467+ ),
468468+ cumulative_counts AS (
469469+ SELECT
470470+ ptg.period,
471471+ ptg.access_type,
472472+ SUM(COALESCE(pc.period_count, 0)) OVER (
473473+ PARTITION BY ptg.access_type
474474+ ORDER BY ptg.period
475475+ ) AS cumulative_count
476476+ FROM period_type_grid ptg
477477+ LEFT JOIN period_counts pc ON ptg.period = pc.period AND ptg.access_type = pc.access_type
448478 ),
449479 collection_aggregated AS (
450480 SELECT
451481 period::text AS date,
452482 jsonb_object_agg(access_type, cumulative_count) AS by_access_type,
453483 SUM(cumulative_count)::int AS total
454454- FROM (
455455- SELECT
456456- period,
457457- access_type,
458458- SUM(period_count) OVER (
459459- PARTITION BY access_type
460460- ORDER BY period
461461- ) AS cumulative_count
462462- FROM period_collection_counts
463463- ) cumulative_data
484484+ FROM cumulative_counts
464485 GROUP BY period
465486 ORDER BY period DESC
466487 LIMIT ${limit}