var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var statistics_exports = {};
__export(statistics_exports, {
  anonymousGraphQLOperationAttributeStatistics: () => anonymousGraphQLOperationAttributeStatistics,
  anonymousGraphQLOperationStatistics: () => anonymousGraphQLOperationStatistics,
  graphQLOperationAttributeStatistics: () => graphQLOperationAttributeStatistics,
  graphQLOperationStatistics: () => graphQLOperationStatistics,
  spanAttributeStatistics: () => spanAttributeStatistics,
  spanStatistics: () => spanStatistics,
  sqlStatementAttributeStatistics: () => sqlStatementAttributeStatistics,
  sqlStatementStatistics: () => sqlStatementStatistics
});
module.exports = __toCommonJS(statistics_exports);
var import_db = require("../../lib/db");
const spanStatistics = async ({
  typeId,
  attributeKey,
  attributeValue,
  intervalMins = 1
}) => {
  return import_db.db.$queryRaw`
  WITH t1 AS (
    SELECT
      strftime ('%Y-%m-%dT%H:%M:%SZ',
        ROUND(strftime ('%s',
            datetime (s.startTimeNano / 1000000000.000,
              'unixepoch')) / (${intervalMins} * 60)) * (${intervalMins} * 60),
        'unixepoch') AS intervalStartedAt,
      CAST((s.endTimeNano - s.startTimeNano) AS NUMERIC) AS duration
    FROM
      OTelTraceSpan s
      JOIN OTelTraceSpanType t ON t. "id" = s.typeId
    -- here we use the Prisma implicit join table to join attributes A to spans B
    JOIN _OTelTraceAttributeToOTelTraceSpan atos on atos.A = a.id and atos.B = s.id
    JOIN OTelTraceAttribute a ON atos.A = a.id
  WHERE
    t.id = ${typeId}
    AND (${attributeKey} IS NULL OR a.key = ${attributeKey})
    AND (${attributeValue} IS NULL OR a.value = ${attributeValue})
  ),
  t2 AS (
    SELECT
      count (intervalStartedAt) AS statisticCount,
      intervalStartedAt,
      MIN(duration) AS minDuration,
      MAX(duration) AS maxDuration,
      AVG(duration) AS avgDuration
    FROM
      t1
    GROUP BY
      intervalStartedAt
  )
  SELECT
    statisticCount,
    intervalStartedAt,
    ROUND(minDuration, 3) AS minDuration,
    ROUND(maxDuration, 3) AS maxDuration,
    ROUND(avgDuration, 3) AS avgDuration,
    ROUND(CAST((minDuration / 1000000.000) AS REAL), 3) AS minDurationMs,
    ROUND(CAST((minDuration / 1000000000.000) AS REAL), 3) AS minDurationSec,
    ROUND(CAST((maxDuration / 1000000.000) AS REAL), 3) AS maxDurationMs,
    ROUND(CAST((maxDuration / 1000000000.000) AS REAL), 3) AS maxDurationSec,
    ROUND(CAST((avgDuration / 1000000.000) AS REAL), 3) AS avgDurationMs,
    ROUND(CAST((avgDuration / 1000000000.000) AS REAL), 3) AS avgDurationSec
  FROM
    t2
  ORDER BY statisticCount DESC, intervalStartedAt DESC`;
};
const sqlStatementStatistics = async ({
  intervalMins
}) => {
  const typeId = "SQL";
  const attributeKey = "db.statement";
  return await spanStatistics({
    typeId,
    attributeKey,
    intervalMins
  });
};
const graphQLOperationStatistics = async ({
  intervalMins
}) => {
  const typeId = "GRAPHQL";
  const attributeKey = "graphql.execute.operationName";
  return await spanStatistics({
    typeId,
    attributeKey,
    intervalMins
  });
};
const anonymousGraphQLOperationStatistics = async ({
  intervalMins
}) => {
  const typeId = "GRAPHQL";
  const attributeKey = "graphql.execute.operationName";
  const attributeValue = '"Anonymous Operation"';
  return await spanStatistics({
    typeId,
    attributeKey,
    attributeValue,
    intervalMins
  });
};
const spanAttributeStatistics = async ({
  typeId,
  attributeKey,
  attributeValue
}) => {
  return import_db.db.$queryRaw`WITH t1 AS (
	SELECT
		CASE WHEN a.type = 'string' THEN
			substr((substr(a.value,
					1,
					instr(a.value,
						' /* traceparent=') - 1) || substr(a.value,
					instr(a.value,
						'*/') + 1)),
			2,
			length((substr(a.value,
					1,
					instr(a.value,
						' /* traceparent=') - 1) || substr(a.value,
					instr(a.value,
						'*/') + 1))) - 2)
		ELSE
			cast(a.value AS text)
		END AS attributeValue,
		CAST((s.endTimeNano - s.startTimeNano) AS NUMERIC) AS duration
	FROM
		OTelTraceSpan s
		JOIN OTelTraceSpanType t ON t. "id" = s.typeId
		-- here we use the Prisma implicit join table to join attributes A to spans B
		JOIN _OTelTraceAttributeToOTelTraceSpan atos ON atos.A = a.id
			AND atos.B = s.id
		JOIN OTelTraceAttribute a ON atos.A = a.id
  WHERE
    t.id = ${typeId}
    AND (${attributeKey} IS NULL OR a.key = ${attributeKey})
    AND (${attributeValue} IS NULL OR a.value = ${attributeValue})
),
t2 AS (
	SELECT
		count(attributeValue) AS statisticCount,
		attributeValue,
		MIN(duration) AS minDuration,
		MAX(duration) AS maxDuration,
		AVG(duration) AS avgDuration
	FROM
		t1
	GROUP BY
		attributeValue
)
SELECT
  statisticCount,
	attributeValue,
	ROUND(minDuration, 3) AS minDuration,
	ROUND(maxDuration, 3) AS maxDuration,
  ROUND(avgDuration, 3) AS avgDuration,
  ROUND(CAST((minDuration / 1000000.000) AS REAL), 3) AS minDurationMs,
	ROUND(CAST((minDuration / 1000000000.000) AS REAL), 3) AS minDurationSec,
	ROUND(CAST((maxDuration / 1000000.000) AS REAL), 3) AS maxDurationMs,
	ROUND(CAST((maxDuration / 1000000000.000) AS REAL), 3) AS maxDurationSec,
	ROUND(CAST((avgDuration / 1000000.000) AS REAL), 3) AS avgDurationMs,
	ROUND(CAST((avgDuration / 1000000000.000) AS REAL), 3) AS avgDurationSec
FROM
	t2
ORDER BY 1 DESC, 2 DESC;`;
};
const sqlStatementAttributeStatistics = async () => {
  const typeId = "SQL";
  const attributeKey = "db.statement";
  return await spanAttributeStatistics({
    typeId,
    attributeKey
  });
};
const graphQLOperationAttributeStatistics = async () => {
  const typeId = "GRAPHQL";
  const attributeKey = "graphql.execute.operationName";
  return await spanAttributeStatistics({
    typeId,
    attributeKey
  });
};
const anonymousGraphQLOperationAttributeStatistics = async () => {
  const typeId = "GRAPHQL";
  const attributeKey = "graphql.execute.operationName";
  const attributeValue = '"Anonymous Operation"';
  return await spanAttributeStatistics({
    typeId,
    attributeKey,
    attributeValue
  });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  anonymousGraphQLOperationAttributeStatistics,
  anonymousGraphQLOperationStatistics,
  graphQLOperationAttributeStatistics,
  graphQLOperationStatistics,
  spanAttributeStatistics,
  spanStatistics,
  sqlStatementAttributeStatistics,
  sqlStatementStatistics
});
//# sourceMappingURL=statistics.js.map
