package sql import ( "context" ) type SummarizeGVKsRow struct { APIVersionCount int `json:"c0"` APIVersion string `json:"api_version"` KindCount int `json:"c1"` Kind string `json:"kind"` } // SummarizeGVKs gives a high level rollup-style summary of watched resources across all clusters, counting // by apiVersion and kind. // For example: // c0 api_version c1 kind // 614 "iam.cnrm.cloud.google.com/v1beta1" 532 "IAMPolicyMember" // 614 "iam.cnrm.cloud.google.com/v1beta1" 41 "IAMPartialPolicy" // 614 "iam.cnrm.cloud.google.com/v1beta1" 21 "IAMServiceAccount" // 614 "iam.cnrm.cloud.google.com/v1beta1" 15 "IAMServiceAccountKey" // 614 "iam.cnrm.cloud.google.com/v1beta1" 5 "IAMCustomRole" // 230 "serviceusage.cnrm.cloud.google.com/v1beta1" 230 "Service" // 127 "compute.cnrm.cloud.google.com/v1beta1" 97 "ComputeFirewall" // shows the total count of all resources in group version, followed by a break down of which kinds contribute // to that count. func (db *DBHandle) SummarizeGVKs(ctx context.Context) ([]SummarizeGVKsRow, error) { query := ` SELECT max(c0) AS c0, max(api_version) AS api_version, max(c1) AS c1, kind FROM ( SELECT COUNT(*) over (PARTITION by api_version) AS c0, api_version, COUNT(*) over (PARTITION by kind) AS c1, kind FROM watched_resources ORDER BY c0 DESC, c1 DESC ) AS agg GROUP BY kind ORDER BY c0 DESC, c1 DESC ` rows, err := db.QueryContext(ctx, query) if err != nil { return nil, err } defer rows.Close() var results []SummarizeGVKsRow for rows.Next() { var result SummarizeGVKsRow if err := rows.Scan(&result.APIVersionCount, &result.APIVersion, &result.KindCount, &result.Kind); err != nil { return results, err } results = append(results, result) } if err := rows.Err(); err != nil { return results, err } return results, nil } type CountByGVKRows struct { Count int `json:"c"` APIVersion string `json:"api_version"` Kind string `json:"kind"` } // CountByGVK gives a simple count summary of watched resources across all clusters, counting // by apiVersion and kind. This is a more efficient, unsorted query suitable for gathering metrics data. func (db *DBHandle) CountByGVK(ctx context.Context) ([]CountByGVKRows, error) { query := ` SELECT COUNT(*) as c, api_version, kind FROM watched_resources GROUP BY api_version, kind ` rows, err := db.QueryContext(ctx, query) if err != nil { return nil, err } defer rows.Close() var results []CountByGVKRows for rows.Next() { var result CountByGVKRows if err := rows.Scan(&result.Count, &result.APIVersion, &result.Kind); err != nil { return results, err } results = append(results, result) } if err := rows.Err(); err != nil { return results, err } return results, nil }