// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.29.0
// source: otel.sql

package sqlcv1

import (
	"context"

	"github.com/google/uuid"
	"github.com/jackc/pgx/v5/pgtype"
)

const insertOTelTraceLookup = `-- name: InsertOTelTraceLookup :exec
WITH inputs AS (
    SELECT
        UNNEST($1::UUID[]) AS tenant_id,
        UNNEST($2::UUID[]) AS external_id,
        UNNEST($3::INT[]) AS retry_count,
        UNNEST($4::BYTEA[]) AS trace_id,
        UNNEST($5::TIMESTAMPTZ[]) AS start_time
)
INSERT INTO v1_otel_trace_lookup_olap (
    tenant_id,
    external_id,
    retry_count,
    trace_id,
    start_time
)
SELECT
    tenant_id,
    external_id,
    retry_count,
    trace_id,
    start_time
FROM inputs
ORDER BY tenant_id, external_id, retry_count, start_time
ON CONFLICT (tenant_id, external_id, retry_count, start_time) DO NOTHING
`

type InsertOTelTraceLookupParams struct {
	Tenantids   []uuid.UUID          `json:"tenantids"`
	Externalids []uuid.UUID          `json:"externalids"`
	Retrycounts []int32              `json:"retrycounts"`
	Traceids    [][]byte             `json:"traceids"`
	Starttimes  []pgtype.Timestamptz `json:"starttimes"`
}

func (q *Queries) InsertOTelTraceLookup(ctx context.Context, db DBTX, arg InsertOTelTraceLookupParams) error {
	_, err := db.Exec(ctx, insertOTelTraceLookup,
		arg.Tenantids,
		arg.Externalids,
		arg.Retrycounts,
		arg.Traceids,
		arg.Starttimes,
	)
	return err
}

const insertOtelSpans = `-- name: InsertOtelSpans :exec
WITH inputs AS (
    SELECT
        UNNEST($1::UUID[]) AS tenant_id,
        UNNEST($2::BYTEA[]) AS trace_id,
        UNNEST($3::BYTEA[]) AS span_id,
        UNNEST($4::TEXT[]) AS parent_span_id,
        UNNEST($5::TEXT[]) AS span_name,
        UNNEST(CAST($6::TEXT[] AS v1_otel_span_kind[])) AS span_kind,
        UNNEST($7::TEXT[]) AS service_name,
        UNNEST(CAST($8::TEXT[] AS v1_otel_status_code[])) AS status_code,
        UNNEST($9::TEXT[]) AS status_message,
        UNNEST($10::BIGINT[]) AS duration_ns,
        UNNEST($11::JSONB[]) AS resource_attributes,
        UNNEST($12::JSONB[]) AS span_attributes,
        UNNEST($13::TEXT[]) AS scope_name,
        UNNEST($14::TEXT[]) AS scope_version,
        UNNEST($15::UUID[]) AS task_run_external_id,
        UNNEST($16::UUID[]) AS workflow_run_external_id,
        UNNEST($17::INT[]) AS retry_count,
        UNNEST($18::TIMESTAMPTZ[]) AS start_time
)

INSERT INTO v1_otel_trace_olap (
    tenant_id,
    trace_id,
    span_id,
    parent_span_id,
    span_name,
    span_kind,
    service_name,
    status_code,
    status_message,
    duration_ns,
    resource_attributes,
    span_attributes,
    scope_name,
    scope_version,
    task_run_external_id,
    workflow_run_external_id,
    retry_count,
    start_time
)
SELECT
    tenant_id,
    trace_id,
    span_id,
    NULLIF(parent_span_id, '') AS parent_span_id,
    span_name,
    span_kind,
    service_name,
    status_code,
    NULLIF(status_message, '') AS status_message,
    duration_ns,
    NULLIF(resource_attributes, '{}'::JSONB) AS resource_attributes,
    NULLIF(span_attributes, '{}'::JSONB) AS span_attributes,
    NULLIF(scope_name, '') AS scope_name,
    NULLIF(scope_version, '') AS scope_version,
    NULLIF(task_run_external_id::TEXT, '00000000-0000-0000-0000-000000000000')::UUID AS task_run_external_id,
    NULLIF(workflow_run_external_id::TEXT, '00000000-0000-0000-0000-000000000000')::UUID AS workflow_run_external_id,
    retry_count,
    start_time
FROM inputs
ORDER BY tenant_id, trace_id, start_time, span_id
ON CONFLICT (tenant_id, trace_id, start_time, span_id) DO NOTHING
`

type InsertOtelSpansParams struct {
	Tenantids              []uuid.UUID          `json:"tenantids"`
	Traceids               [][]byte             `json:"traceids"`
	Spanids                [][]byte             `json:"spanids"`
	Parentspanids          []string             `json:"parentspanids"`
	Spannames              []string             `json:"spannames"`
	Spankinds              []string             `json:"spankinds"`
	Servicenames           []string             `json:"servicenames"`
	Statuscodes            []string             `json:"statuscodes"`
	Statusmessages         []string             `json:"statusmessages"`
	Durationnss            []int64              `json:"durationnss"`
	Resourceattributes     [][]byte             `json:"resourceattributes"`
	Spanattributes         [][]byte             `json:"spanattributes"`
	Scopenames             []string             `json:"scopenames"`
	Scopeversions          []string             `json:"scopeversions"`
	Taskrunexternalids     []uuid.UUID          `json:"taskrunexternalids"`
	Workflowrunexternalids []uuid.UUID          `json:"workflowrunexternalids"`
	Retrycounts            []int32              `json:"retrycounts"`
	Starttimes             []pgtype.Timestamptz `json:"starttimes"`
}

func (q *Queries) InsertOtelSpans(ctx context.Context, db DBTX, arg InsertOtelSpansParams) error {
	_, err := db.Exec(ctx, insertOtelSpans,
		arg.Tenantids,
		arg.Traceids,
		arg.Spanids,
		arg.Parentspanids,
		arg.Spannames,
		arg.Spankinds,
		arg.Servicenames,
		arg.Statuscodes,
		arg.Statusmessages,
		arg.Durationnss,
		arg.Resourceattributes,
		arg.Spanattributes,
		arg.Scopenames,
		arg.Scopeversions,
		arg.Taskrunexternalids,
		arg.Workflowrunexternalids,
		arg.Retrycounts,
		arg.Starttimes,
	)
	return err
}

const listSpansByTraceId = `-- name: ListSpansByTraceId :many
SELECT tenant_id, trace_id, span_id, parent_span_id, span_name, span_kind, service_name, status_code, status_message, duration_ns, resource_attributes, span_attributes, scope_name, scope_version, task_run_external_id, workflow_run_external_id, retry_count, start_time
FROM v1_otel_trace_olap
WHERE
    tenant_id = $1::UUID
    AND trace_id = $2::BYTEA
ORDER BY start_time ASC
OFFSET COALESCE($3::BIGINT, 0)
LIMIT COALESCE($4::BIGINT, 1000)
`

type ListSpansByTraceIdParams struct {
	Tenantid   uuid.UUID `json:"tenantid"`
	Traceid    []byte    `json:"traceid"`
	Spanoffset int64     `json:"spanoffset"`
	Spanlimit  int64     `json:"spanlimit"`
}

func (q *Queries) ListSpansByTraceId(ctx context.Context, db DBTX, arg ListSpansByTraceIdParams) ([]*V1OtelTraceOlap, error) {
	rows, err := db.Query(ctx, listSpansByTraceId,
		arg.Tenantid,
		arg.Traceid,
		arg.Spanoffset,
		arg.Spanlimit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*V1OtelTraceOlap
	for rows.Next() {
		var i V1OtelTraceOlap
		if err := rows.Scan(
			&i.TenantID,
			&i.TraceID,
			&i.SpanID,
			&i.ParentSpanID,
			&i.SpanName,
			&i.SpanKind,
			&i.ServiceName,
			&i.StatusCode,
			&i.StatusMessage,
			&i.DurationNs,
			&i.ResourceAttributes,
			&i.SpanAttributes,
			&i.ScopeName,
			&i.ScopeVersion,
			&i.TaskRunExternalID,
			&i.WorkflowRunExternalID,
			&i.RetryCount,
			&i.StartTime,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lookUpTraceId = `-- name: LookUpTraceId :one
WITH candidate_traces AS (
    SELECT tenant_id, external_id, retry_count, trace_id, start_time
    FROM v1_otel_trace_lookup_olap
    WHERE
        tenant_id = $1::UUID
        AND external_id = $2::UUID
)

SELECT trace_id
FROM candidate_traces
ORDER BY retry_count DESC, start_time DESC
LIMIT 1
`

type LookUpTraceIdParams struct {
	Tenantid   uuid.UUID `json:"tenantid"`
	Externalid uuid.UUID `json:"externalid"`
}

// get the max retry count + use time as a stable-ish order
func (q *Queries) LookUpTraceId(ctx context.Context, db DBTX, arg LookUpTraceIdParams) ([]byte, error) {
	row := db.QueryRow(ctx, lookUpTraceId, arg.Tenantid, arg.Externalid)
	var trace_id []byte
	err := row.Scan(&trace_id)
	return trace_id, err
}
