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

package sqlcv1

import (
	"context"

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

const addStepParents = `-- name: AddStepParents :exec
INSERT INTO "_StepOrder" ("A", "B")
SELECT
    step."id",
    $1::uuid
FROM
    unnest($2::text[]) AS parent_readable_id
JOIN
    "Step" AS step ON step."readableId" = parent_readable_id AND step."jobId" = $3::uuid
`

type AddStepParentsParams struct {
	ID      uuid.UUID `json:"id"`
	Parents []string  `json:"parents"`
	Jobid   uuid.UUID `json:"jobid"`
}

func (q *Queries) AddStepParents(ctx context.Context, db DBTX, arg AddStepParentsParams) error {
	_, err := db.Exec(ctx, addStepParents, arg.ID, arg.Parents, arg.Jobid)
	return err
}

const countWorkflows = `-- name: CountWorkflows :one
SELECT COUNT(w.*)
FROM "Workflow" w
WHERE
    w."tenantId" = $1
    AND w."deletedAt" IS NULL
    AND (
        $2::TEXT IS NULL OR
        w."id" IN (
            SELECT
                DISTINCT ON(t1."workflowId") t1."workflowId"
            FROM
                "WorkflowVersion" AS t1
                LEFT JOIN "WorkflowTriggers" AS j2 ON j2."workflowVersionId" = t1."id"
            WHERE
                (
                    j2."id" IN (
                        SELECT
                            t3."parentId"
                        FROM
                            "WorkflowTriggerEventRef" AS t3
                        WHERE
                            t3."eventKey" = $2::text
                            AND t3."parentId" IS NOT NULL
                    )
                    AND j2."id" IS NOT NULL
                    AND t1."workflowId" IS NOT NULL
                )
            ORDER BY
                t1."workflowId" DESC, t1."order" DESC
        )
    )
    AND (
        $3::TEXT IS NULL
        OR w.name ILIKE CONCAT('%', $3::TEXT, '%')
    )
`

type CountWorkflowsParams struct {
	TenantId uuid.UUID   `json:"tenantId"`
	EventKey pgtype.Text `json:"eventKey"`
	Search   pgtype.Text `json:"search"`
}

func (q *Queries) CountWorkflows(ctx context.Context, db DBTX, arg CountWorkflowsParams) (int64, error) {
	row := db.QueryRow(ctx, countWorkflows, arg.TenantId, arg.EventKey, arg.Search)
	var count int64
	err := row.Scan(&count)
	return count, err
}

const createJob = `-- name: CreateJob :one
INSERT INTO "Job" (
    "id",
    "createdAt",
    "updatedAt",
    "deletedAt",
    "tenantId",
    "workflowVersionId",
    "name",
    "description",
    "timeout",
    "kind"
) VALUES (
    $1::uuid,
    coalesce($2::timestamp, CURRENT_TIMESTAMP),
    coalesce($3::timestamp, CURRENT_TIMESTAMP),
    $4::timestamp,
    $5::uuid,
    $6::uuid,
    $7::text,
    $8::text,
    -- Deprecated: this is set but unused
    '5m',
    coalesce($9::"JobKind", 'DEFAULT')
) RETURNING id, "createdAt", "updatedAt", "deletedAt", "tenantId", "workflowVersionId", name, description, timeout, kind
`

type CreateJobParams struct {
	ID                uuid.UUID        `json:"id"`
	CreatedAt         pgtype.Timestamp `json:"createdAt"`
	UpdatedAt         pgtype.Timestamp `json:"updatedAt"`
	Deletedat         pgtype.Timestamp `json:"deletedat"`
	Tenantid          uuid.UUID        `json:"tenantid"`
	Workflowversionid uuid.UUID        `json:"workflowversionid"`
	Name              string           `json:"name"`
	Description       string           `json:"description"`
	Kind              NullJobKind      `json:"kind"`
}

func (q *Queries) CreateJob(ctx context.Context, db DBTX, arg CreateJobParams) (*Job, error) {
	row := db.QueryRow(ctx, createJob,
		arg.ID,
		arg.CreatedAt,
		arg.UpdatedAt,
		arg.Deletedat,
		arg.Tenantid,
		arg.Workflowversionid,
		arg.Name,
		arg.Description,
		arg.Kind,
	)
	var i Job
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DeletedAt,
		&i.TenantId,
		&i.WorkflowVersionId,
		&i.Name,
		&i.Description,
		&i.Timeout,
		&i.Kind,
	)
	return &i, err
}

const createStep = `-- name: CreateStep :one
INSERT INTO "Step" (
    "id",
    "createdAt",
    "updatedAt",
    "deletedAt",
    "readableId",
    "tenantId",
    "jobId",
    "actionId",
    "timeout",
    "customUserData",
    "retries",
    "scheduleTimeout",
    "retryBackoffFactor",
    "retryMaxBackoff",
    "isDurable"
) VALUES (
    $1::uuid,
    coalesce($2::timestamp, CURRENT_TIMESTAMP),
    coalesce($3::timestamp, CURRENT_TIMESTAMP),
    $4::timestamp,
    $5::text,
    $6::uuid,
    $7::uuid,
    $8::text,
    $9::text,
    coalesce($10::jsonb, '{}'),
    coalesce($11::integer, 0),
    coalesce($12::text, '5m'),
    $13,
    $14,
    coalesce($15::boolean, false)
) RETURNING id, "createdAt", "updatedAt", "deletedAt", "readableId", "tenantId", "jobId", "actionId", timeout, "customUserData", retries, "retryBackoffFactor", "retryMaxBackoff", "scheduleTimeout", "isDurable"
`

type CreateStepParams struct {
	ID                 uuid.UUID        `json:"id"`
	CreatedAt          pgtype.Timestamp `json:"createdAt"`
	UpdatedAt          pgtype.Timestamp `json:"updatedAt"`
	Deletedat          pgtype.Timestamp `json:"deletedat"`
	Readableid         string           `json:"readableid"`
	Tenantid           uuid.UUID        `json:"tenantid"`
	Jobid              uuid.UUID        `json:"jobid"`
	Actionid           string           `json:"actionid"`
	Timeout            pgtype.Text      `json:"timeout"`
	CustomUserData     []byte           `json:"customUserData"`
	Retries            pgtype.Int4      `json:"retries"`
	ScheduleTimeout    pgtype.Text      `json:"scheduleTimeout"`
	RetryBackoffFactor pgtype.Float8    `json:"retryBackoffFactor"`
	RetryMaxBackoff    pgtype.Int4      `json:"retryMaxBackoff"`
	IsDurable          pgtype.Bool      `json:"isDurable"`
}

func (q *Queries) CreateStep(ctx context.Context, db DBTX, arg CreateStepParams) (*Step, error) {
	row := db.QueryRow(ctx, createStep,
		arg.ID,
		arg.CreatedAt,
		arg.UpdatedAt,
		arg.Deletedat,
		arg.Readableid,
		arg.Tenantid,
		arg.Jobid,
		arg.Actionid,
		arg.Timeout,
		arg.CustomUserData,
		arg.Retries,
		arg.ScheduleTimeout,
		arg.RetryBackoffFactor,
		arg.RetryMaxBackoff,
		arg.IsDurable,
	)
	var i Step
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DeletedAt,
		&i.ReadableId,
		&i.TenantId,
		&i.JobId,
		&i.ActionId,
		&i.Timeout,
		&i.CustomUserData,
		&i.Retries,
		&i.RetryBackoffFactor,
		&i.RetryMaxBackoff,
		&i.ScheduleTimeout,
		&i.IsDurable,
	)
	return &i, err
}

const createStepConcurrency = `-- name: CreateStepConcurrency :one
INSERT INTO v1_step_concurrency (
    workflow_id,
    workflow_version_id,
    step_id,
    strategy,
    expression,
    tenant_id,
    max_concurrency
)
VALUES (
    $1::uuid,
    $2::uuid,
    $3::uuid,
    $4::v1_concurrency_strategy,
    $5::text,
    $6::uuid,
    $7::integer
) RETURNING id, parent_strategy_id, workflow_id, workflow_version_id, step_id, is_active, strategy, expression, tenant_id, max_concurrency
`

type CreateStepConcurrencyParams struct {
	Workflowid        uuid.UUID             `json:"workflowid"`
	Workflowversionid uuid.UUID             `json:"workflowversionid"`
	Stepid            uuid.UUID             `json:"stepid"`
	Strategy          V1ConcurrencyStrategy `json:"strategy"`
	Expression        string                `json:"expression"`
	Tenantid          uuid.UUID             `json:"tenantid"`
	Maxconcurrency    int32                 `json:"maxconcurrency"`
}

func (q *Queries) CreateStepConcurrency(ctx context.Context, db DBTX, arg CreateStepConcurrencyParams) (*V1StepConcurrency, error) {
	row := db.QueryRow(ctx, createStepConcurrency,
		arg.Workflowid,
		arg.Workflowversionid,
		arg.Stepid,
		arg.Strategy,
		arg.Expression,
		arg.Tenantid,
		arg.Maxconcurrency,
	)
	var i V1StepConcurrency
	err := row.Scan(
		&i.ID,
		&i.ParentStrategyID,
		&i.WorkflowID,
		&i.WorkflowVersionID,
		&i.StepID,
		&i.IsActive,
		&i.Strategy,
		&i.Expression,
		&i.TenantID,
		&i.MaxConcurrency,
	)
	return &i, err
}

const createStepExpressions = `-- name: CreateStepExpressions :exec
INSERT INTO "StepExpression" (
    "key",
    "stepId",
    "expression",
    "kind"
) VALUES (
    unnest($1::text[]),
    $2::uuid,
    unnest($3::text[]),
    unnest(cast($4::text[] as"StepExpressionKind"[]))
) ON CONFLICT ("key", "stepId", "kind") DO UPDATE
SET
    "expression" = EXCLUDED."expression"
`

type CreateStepExpressionsParams struct {
	Keys        []string  `json:"keys"`
	Stepid      uuid.UUID `json:"stepid"`
	Expressions []string  `json:"expressions"`
	Kinds       []string  `json:"kinds"`
}

func (q *Queries) CreateStepExpressions(ctx context.Context, db DBTX, arg CreateStepExpressionsParams) error {
	_, err := db.Exec(ctx, createStepExpressions,
		arg.Keys,
		arg.Stepid,
		arg.Expressions,
		arg.Kinds,
	)
	return err
}

const createStepMatchCondition = `-- name: CreateStepMatchCondition :one
INSERT INTO v1_step_match_condition (
    tenant_id,
    step_id,
    readable_data_key,
    action,
    or_group_id,
    expression,
    kind,
    sleep_duration,
    event_key,
    parent_readable_id
)
VALUES (
    $1::uuid,
    $2::uuid,
    $3::text,
    $4::v1_match_condition_action,
    $5::uuid,
    $6::text,
    $7::v1_step_match_condition_kind,
    $8::text,
    $9::text,
    $10::text
) RETURNING id, tenant_id, step_id, readable_data_key, action, or_group_id, expression, kind, sleep_duration, event_key, parent_readable_id
`

type CreateStepMatchConditionParams struct {
	Tenantid         uuid.UUID                `json:"tenantid"`
	Stepid           uuid.UUID                `json:"stepid"`
	Readabledatakey  string                   `json:"readabledatakey"`
	Action           V1MatchConditionAction   `json:"action"`
	Orgroupid        uuid.UUID                `json:"orgroupid"`
	Expression       pgtype.Text              `json:"expression"`
	Kind             V1StepMatchConditionKind `json:"kind"`
	SleepDuration    pgtype.Text              `json:"sleepDuration"`
	EventKey         pgtype.Text              `json:"eventKey"`
	ParentReadableId pgtype.Text              `json:"parentReadableId"`
}

func (q *Queries) CreateStepMatchCondition(ctx context.Context, db DBTX, arg CreateStepMatchConditionParams) (*V1StepMatchCondition, error) {
	row := db.QueryRow(ctx, createStepMatchCondition,
		arg.Tenantid,
		arg.Stepid,
		arg.Readabledatakey,
		arg.Action,
		arg.Orgroupid,
		arg.Expression,
		arg.Kind,
		arg.SleepDuration,
		arg.EventKey,
		arg.ParentReadableId,
	)
	var i V1StepMatchCondition
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.StepID,
		&i.ReadableDataKey,
		&i.Action,
		&i.OrGroupID,
		&i.Expression,
		&i.Kind,
		&i.SleepDuration,
		&i.EventKey,
		&i.ParentReadableID,
	)
	return &i, err
}

const createStepRateLimit = `-- name: CreateStepRateLimit :one
INSERT INTO "StepRateLimit" (
    "units",
    "stepId",
    "rateLimitKey",
    "tenantId",
    "kind"
) VALUES (
    $1::integer,
    $2::uuid,
    $3::text,
    $4::uuid,
    $5
) RETURNING units, "stepId", "rateLimitKey", "tenantId", kind
`

type CreateStepRateLimitParams struct {
	Units        int32             `json:"units"`
	Stepid       uuid.UUID         `json:"stepid"`
	Ratelimitkey string            `json:"ratelimitkey"`
	Tenantid     uuid.UUID         `json:"tenantid"`
	Kind         StepRateLimitKind `json:"kind"`
}

func (q *Queries) CreateStepRateLimit(ctx context.Context, db DBTX, arg CreateStepRateLimitParams) (*StepRateLimit, error) {
	row := db.QueryRow(ctx, createStepRateLimit,
		arg.Units,
		arg.Stepid,
		arg.Ratelimitkey,
		arg.Tenantid,
		arg.Kind,
	)
	var i StepRateLimit
	err := row.Scan(
		&i.Units,
		&i.StepId,
		&i.RateLimitKey,
		&i.TenantId,
		&i.Kind,
	)
	return &i, err
}

const createStepSlotRequests = `-- name: CreateStepSlotRequests :exec
INSERT INTO v1_step_slot_request (
    tenant_id,
    step_id,
    slot_type,
    units,
    created_at,
    updated_at
)
SELECT
    $1::uuid,
    $2::uuid,
    unnest($3::text[]),
    unnest($4::integer[]),
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP
ON CONFLICT (tenant_id, step_id, slot_type) DO NOTHING
`

type CreateStepSlotRequestsParams struct {
	Tenantid  uuid.UUID `json:"tenantid"`
	Stepid    uuid.UUID `json:"stepid"`
	Slottypes []string  `json:"slottypes"`
	Units     []int32   `json:"units"`
}

// NOTE: ON CONFLICT can be removed after the 0_76_d migration is run to remove insert triggers added in 0_76
func (q *Queries) CreateStepSlotRequests(ctx context.Context, db DBTX, arg CreateStepSlotRequestsParams) error {
	_, err := db.Exec(ctx, createStepSlotRequests,
		arg.Tenantid,
		arg.Stepid,
		arg.Slottypes,
		arg.Units,
	)
	return err
}

const createWorkflow = `-- name: CreateWorkflow :one
INSERT INTO "Workflow" (
    "id",
    "createdAt",
    "updatedAt",
    "deletedAt",
    "tenantId",
    "name",
    "description"
) VALUES (
    $1::uuid,
    coalesce($2::timestamp, CURRENT_TIMESTAMP),
    coalesce($3::timestamp, CURRENT_TIMESTAMP),
    $4::timestamp,
    $5::uuid,
    $6::text,
    $7::text
) RETURNING id, "createdAt", "updatedAt", "deletedAt", "tenantId", name, description, "isPaused"
`

type CreateWorkflowParams struct {
	ID          uuid.UUID        `json:"id"`
	CreatedAt   pgtype.Timestamp `json:"createdAt"`
	UpdatedAt   pgtype.Timestamp `json:"updatedAt"`
	Deletedat   pgtype.Timestamp `json:"deletedat"`
	Tenantid    uuid.UUID        `json:"tenantid"`
	Name        string           `json:"name"`
	Description string           `json:"description"`
}

func (q *Queries) CreateWorkflow(ctx context.Context, db DBTX, arg CreateWorkflowParams) (*Workflow, error) {
	row := db.QueryRow(ctx, createWorkflow,
		arg.ID,
		arg.CreatedAt,
		arg.UpdatedAt,
		arg.Deletedat,
		arg.Tenantid,
		arg.Name,
		arg.Description,
	)
	var i Workflow
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DeletedAt,
		&i.TenantId,
		&i.Name,
		&i.Description,
		&i.IsPaused,
	)
	return &i, err
}

const createWorkflowConcurrency = `-- name: CreateWorkflowConcurrency :one
INSERT INTO "WorkflowConcurrency" (
    "id",
    "createdAt",
    "updatedAt",
    "workflowVersionId",
    "getConcurrencyGroupId",
    "maxRuns",
    "limitStrategy",
    "concurrencyGroupExpression"
) VALUES (
    gen_random_uuid(),
    coalesce($1::timestamp, CURRENT_TIMESTAMP),
    coalesce($2::timestamp, CURRENT_TIMESTAMP),
    $3::uuid,
    $4::uuid,
    coalesce($5::integer, 1),
    coalesce($6::"ConcurrencyLimitStrategy", 'CANCEL_IN_PROGRESS'),
    $7::text
) RETURNING id, "createdAt", "updatedAt", "workflowVersionId", "getConcurrencyGroupId", "maxRuns", "limitStrategy", "concurrencyGroupExpression"
`

type CreateWorkflowConcurrencyParams struct {
	CreatedAt                  pgtype.Timestamp             `json:"createdAt"`
	UpdatedAt                  pgtype.Timestamp             `json:"updatedAt"`
	Workflowversionid          uuid.UUID                    `json:"workflowversionid"`
	GetConcurrencyGroupId      *uuid.UUID                   `json:"getConcurrencyGroupId"`
	MaxRuns                    pgtype.Int4                  `json:"maxRuns"`
	LimitStrategy              NullConcurrencyLimitStrategy `json:"limitStrategy"`
	ConcurrencyGroupExpression pgtype.Text                  `json:"concurrencyGroupExpression"`
}

func (q *Queries) CreateWorkflowConcurrency(ctx context.Context, db DBTX, arg CreateWorkflowConcurrencyParams) (*WorkflowConcurrency, error) {
	row := db.QueryRow(ctx, createWorkflowConcurrency,
		arg.CreatedAt,
		arg.UpdatedAt,
		arg.Workflowversionid,
		arg.GetConcurrencyGroupId,
		arg.MaxRuns,
		arg.LimitStrategy,
		arg.ConcurrencyGroupExpression,
	)
	var i WorkflowConcurrency
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.WorkflowVersionId,
		&i.GetConcurrencyGroupId,
		&i.MaxRuns,
		&i.LimitStrategy,
		&i.ConcurrencyGroupExpression,
	)
	return &i, err
}

const createWorkflowConcurrencyV1 = `-- name: CreateWorkflowConcurrencyV1 :one
WITH inserted_wcs AS (
    INSERT INTO v1_workflow_concurrency (
      workflow_id,
      workflow_version_id,
      strategy,
      expression,
      tenant_id,
      max_concurrency
    )
    VALUES (
      $1::uuid,
      $2::uuid,
      $3::v1_concurrency_strategy,
      $4,
      $5::uuid,
      COALESCE($6::integer, 1)
    )
    RETURNING id, workflow_id, workflow_version_id, is_active, strategy, child_strategy_ids, expression, tenant_id, max_concurrency
), inserted_scs AS (
    INSERT INTO v1_step_concurrency (
      parent_strategy_id,
      workflow_id,
      workflow_version_id,
      step_id,
      strategy,
      expression,
      tenant_id,
      max_concurrency
    )
    SELECT
      wcs.id,
      s."workflowId",
      s."workflowVersionId",
      s."id",
      $3::v1_concurrency_strategy,
      $4,
      s."tenantId",
      COALESCE($6::integer, 1)
    FROM (
        SELECT
          s."id",
          wf."id" AS "workflowId",
          wv."id" AS "workflowVersionId",
          wf."tenantId"
        FROM "Step" s
        JOIN "Job" j ON s."jobId" = j."id"
        JOIN "WorkflowVersion" wv ON j."workflowVersionId" = wv."id"
        JOIN "Workflow" wf ON wv."workflowId" = wf."id"
        WHERE
          wv."id" = $2::uuid
          AND j."kind" = 'DEFAULT'
    ) s, inserted_wcs wcs
    RETURNING id, parent_strategy_id, workflow_id, workflow_version_id, step_id, is_active, strategy, expression, tenant_id, max_concurrency
)
SELECT
    wcs.id,
    ARRAY_AGG(scs.id)::bigint[] AS child_strategy_ids
FROM
    inserted_wcs wcs
JOIN
    inserted_scs scs ON scs.parent_strategy_id = wcs.id
GROUP BY
    wcs.id
`

type CreateWorkflowConcurrencyV1Params struct {
	Workflowid        uuid.UUID             `json:"workflowid"`
	Workflowversionid uuid.UUID             `json:"workflowversionid"`
	Limitstrategy     V1ConcurrencyStrategy `json:"limitstrategy"`
	Expression        string                `json:"expression"`
	Tenantid          uuid.UUID             `json:"tenantid"`
	MaxRuns           pgtype.Int4           `json:"maxRuns"`
}

type CreateWorkflowConcurrencyV1Row struct {
	ID               int64   `json:"id"`
	ChildStrategyIds []int64 `json:"child_strategy_ids"`
}

func (q *Queries) CreateWorkflowConcurrencyV1(ctx context.Context, db DBTX, arg CreateWorkflowConcurrencyV1Params) (*CreateWorkflowConcurrencyV1Row, error) {
	row := db.QueryRow(ctx, createWorkflowConcurrencyV1,
		arg.Workflowid,
		arg.Workflowversionid,
		arg.Limitstrategy,
		arg.Expression,
		arg.Tenantid,
		arg.MaxRuns,
	)
	var i CreateWorkflowConcurrencyV1Row
	err := row.Scan(&i.ID, &i.ChildStrategyIds)
	return &i, err
}

const createWorkflowTriggerCronRef = `-- name: CreateWorkflowTriggerCronRef :one
WITH previous_trigger AS (
    SELECT "enabled"
    FROM "WorkflowTriggerCronRef" c
    JOIN "WorkflowTriggers" t ON t."id" = c."parentId"
    JOIN "WorkflowVersion" wv ON wv."id" = t."workflowVersionId"
    WHERE
        wv."id" = $8::uuid
        AND "cron" = $2::text
        AND "name" = $3::text
)

INSERT INTO "WorkflowTriggerCronRef" (
    "parentId",
    "cron",
    "name",
    "input",
    "additionalMetadata",
    "id",
    "method",
    "priority",
    "enabled"
)
SELECT
    $1::uuid AS "parentId",
    $2::text AS "cron",
    $3::text AS "name",
    $4::jsonb AS "input",
    $5::jsonb AS "additionalMetadata",
    gen_random_uuid() AS "id",
    COALESCE($6::"WorkflowTriggerCronRefMethods", 'DEFAULT') AS "method",
    COALESCE($7::integer, 1) AS "priority",
    COALESCE((SELECT "enabled" FROM previous_trigger), true) AS "enabled"
RETURNING "parentId", cron, "tickerId", input, enabled, "additionalMetadata", "createdAt", "deletedAt", "updatedAt", name, id, method, priority
`

type CreateWorkflowTriggerCronRefParams struct {
	Workflowtriggersid   uuid.UUID                         `json:"workflowtriggersid"`
	Crontrigger          string                            `json:"crontrigger"`
	Name                 pgtype.Text                       `json:"name"`
	Input                []byte                            `json:"input"`
	AdditionalMetadata   []byte                            `json:"additionalMetadata"`
	Method               NullWorkflowTriggerCronRefMethods `json:"method"`
	Priority             pgtype.Int4                       `json:"priority"`
	OldWorkflowVersionId *uuid.UUID                        `json:"oldWorkflowVersionId"`
}

func (q *Queries) CreateWorkflowTriggerCronRef(ctx context.Context, db DBTX, arg CreateWorkflowTriggerCronRefParams) (*WorkflowTriggerCronRef, error) {
	row := db.QueryRow(ctx, createWorkflowTriggerCronRef,
		arg.Workflowtriggersid,
		arg.Crontrigger,
		arg.Name,
		arg.Input,
		arg.AdditionalMetadata,
		arg.Method,
		arg.Priority,
		arg.OldWorkflowVersionId,
	)
	var i WorkflowTriggerCronRef
	err := row.Scan(
		&i.ParentId,
		&i.Cron,
		&i.TickerId,
		&i.Input,
		&i.Enabled,
		&i.AdditionalMetadata,
		&i.CreatedAt,
		&i.DeletedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.ID,
		&i.Method,
		&i.Priority,
	)
	return &i, err
}

const createWorkflowTriggerCronRefForWorkflow = `-- name: CreateWorkflowTriggerCronRefForWorkflow :one
WITH latest_version AS (
    SELECT "id" FROM "WorkflowVersion"
    WHERE "workflowId" = $7::uuid
    ORDER BY "order" DESC
    LIMIT 1
),
latest_trigger AS (
    SELECT "id" FROM "WorkflowTriggers"
    WHERE "workflowVersionId" = (SELECT "id" FROM latest_version)
    ORDER BY "createdAt" DESC
    LIMIT 1
)
INSERT INTO "WorkflowTriggerCronRef" (
    "parentId",
    "cron",
    "name",
    "input",
    "additionalMetadata",
    "id",
    "method",
    "priority"
) VALUES (
    (SELECT "id" FROM latest_trigger),
    $1::text,
    $2::text,
    $3::jsonb,
    $4::jsonb,
    gen_random_uuid(),
    COALESCE($5::"WorkflowTriggerCronRefMethods", 'DEFAULT'),
    COALESCE($6::integer, 1)
) RETURNING "parentId", cron, "tickerId", input, enabled, "additionalMetadata", "createdAt", "deletedAt", "updatedAt", name, id, method, priority
`

type CreateWorkflowTriggerCronRefForWorkflowParams struct {
	Crontrigger        string                            `json:"crontrigger"`
	Name               pgtype.Text                       `json:"name"`
	Input              []byte                            `json:"input"`
	AdditionalMetadata []byte                            `json:"additionalMetadata"`
	Method             NullWorkflowTriggerCronRefMethods `json:"method"`
	Priority           pgtype.Int4                       `json:"priority"`
	Workflowid         uuid.UUID                         `json:"workflowid"`
}

func (q *Queries) CreateWorkflowTriggerCronRefForWorkflow(ctx context.Context, db DBTX, arg CreateWorkflowTriggerCronRefForWorkflowParams) (*WorkflowTriggerCronRef, error) {
	row := db.QueryRow(ctx, createWorkflowTriggerCronRefForWorkflow,
		arg.Crontrigger,
		arg.Name,
		arg.Input,
		arg.AdditionalMetadata,
		arg.Method,
		arg.Priority,
		arg.Workflowid,
	)
	var i WorkflowTriggerCronRef
	err := row.Scan(
		&i.ParentId,
		&i.Cron,
		&i.TickerId,
		&i.Input,
		&i.Enabled,
		&i.AdditionalMetadata,
		&i.CreatedAt,
		&i.DeletedAt,
		&i.UpdatedAt,
		&i.Name,
		&i.ID,
		&i.Method,
		&i.Priority,
	)
	return &i, err
}

const createWorkflowTriggerEventRef = `-- name: CreateWorkflowTriggerEventRef :one
INSERT INTO "WorkflowTriggerEventRef" (
    "parentId",
    "eventKey"
) VALUES (
    $1::uuid,
    $2::text
) RETURNING "parentId", "eventKey"
`

type CreateWorkflowTriggerEventRefParams struct {
	Workflowtriggersid uuid.UUID `json:"workflowtriggersid"`
	Eventtrigger       string    `json:"eventtrigger"`
}

func (q *Queries) CreateWorkflowTriggerEventRef(ctx context.Context, db DBTX, arg CreateWorkflowTriggerEventRefParams) (*WorkflowTriggerEventRef, error) {
	row := db.QueryRow(ctx, createWorkflowTriggerEventRef, arg.Workflowtriggersid, arg.Eventtrigger)
	var i WorkflowTriggerEventRef
	err := row.Scan(&i.ParentId, &i.EventKey)
	return &i, err
}

const createWorkflowTriggers = `-- name: CreateWorkflowTriggers :one
INSERT INTO "WorkflowTriggers" (
    "id",
    "createdAt",
    "updatedAt",
    "deletedAt",
    "workflowVersionId",
    "tenantId"
) VALUES (
    $1::uuid,
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP,
    NULL,
    $2::uuid,
    $3::uuid
) RETURNING id, "createdAt", "updatedAt", "deletedAt", "workflowVersionId", "tenantId"
`

type CreateWorkflowTriggersParams struct {
	ID                uuid.UUID `json:"id"`
	Workflowversionid uuid.UUID `json:"workflowversionid"`
	Tenantid          uuid.UUID `json:"tenantid"`
}

func (q *Queries) CreateWorkflowTriggers(ctx context.Context, db DBTX, arg CreateWorkflowTriggersParams) (*WorkflowTriggers, error) {
	row := db.QueryRow(ctx, createWorkflowTriggers, arg.ID, arg.Workflowversionid, arg.Tenantid)
	var i WorkflowTriggers
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DeletedAt,
		&i.WorkflowVersionId,
		&i.TenantId,
	)
	return &i, err
}

const createWorkflowVersion = `-- name: CreateWorkflowVersion :one
INSERT INTO "WorkflowVersion" (
    "id",
    "createdAt",
    "updatedAt",
    "deletedAt",
    "checksum",
    "version",
    "workflowId",
    "scheduleTimeout",
    "sticky",
    "kind",
    "defaultPriority",
    "createWorkflowVersionOpts",
    "inputJsonSchema"
) VALUES (
    $1::uuid,
    coalesce($2::timestamp, CURRENT_TIMESTAMP),
    coalesce($3::timestamp, CURRENT_TIMESTAMP),
    $4::timestamp,
    $5::text,
    $6::text,
    $7::uuid,
    -- Deprecated: this is set but unused
    '5m',
    $8::"StickyStrategy",
    coalesce($9::"WorkflowKind", 'DAG'),
    $10 :: integer,
    $11::jsonb,
    $12::jsonb
) RETURNING id, "createdAt", "updatedAt", "deletedAt", version, "order", "workflowId", checksum, "scheduleTimeout", "onFailureJobId", sticky, kind, "defaultPriority", "createWorkflowVersionOpts", "inputJsonSchema"
`

type CreateWorkflowVersionParams struct {
	ID                        uuid.UUID          `json:"id"`
	CreatedAt                 pgtype.Timestamp   `json:"createdAt"`
	UpdatedAt                 pgtype.Timestamp   `json:"updatedAt"`
	Deletedat                 pgtype.Timestamp   `json:"deletedat"`
	Checksum                  string             `json:"checksum"`
	Version                   pgtype.Text        `json:"version"`
	Workflowid                uuid.UUID          `json:"workflowid"`
	Sticky                    NullStickyStrategy `json:"sticky"`
	Kind                      NullWorkflowKind   `json:"kind"`
	DefaultPriority           pgtype.Int4        `json:"defaultPriority"`
	CreateWorkflowVersionOpts []byte             `json:"createWorkflowVersionOpts"`
	InputJsonSchema           []byte             `json:"inputJsonSchema"`
}

func (q *Queries) CreateWorkflowVersion(ctx context.Context, db DBTX, arg CreateWorkflowVersionParams) (*WorkflowVersion, error) {
	row := db.QueryRow(ctx, createWorkflowVersion,
		arg.ID,
		arg.CreatedAt,
		arg.UpdatedAt,
		arg.Deletedat,
		arg.Checksum,
		arg.Version,
		arg.Workflowid,
		arg.Sticky,
		arg.Kind,
		arg.DefaultPriority,
		arg.CreateWorkflowVersionOpts,
		arg.InputJsonSchema,
	)
	var i WorkflowVersion
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DeletedAt,
		&i.Version,
		&i.Order,
		&i.WorkflowId,
		&i.Checksum,
		&i.ScheduleTimeout,
		&i.OnFailureJobId,
		&i.Sticky,
		&i.Kind,
		&i.DefaultPriority,
		&i.CreateWorkflowVersionOpts,
		&i.InputJsonSchema,
	)
	return &i, err
}

const deleteOldDefaultCronTriggersForWorkflowVersion = `-- name: DeleteOldDefaultCronTriggersForWorkflowVersion :exec
DELETE FROM "WorkflowTriggerCronRef"
USING "WorkflowTriggers"
WHERE "WorkflowTriggerCronRef"."parentId" = "WorkflowTriggers"."id"
    AND "WorkflowTriggers"."workflowVersionId" = $1::uuid
    AND "WorkflowTriggerCronRef"."method" = 'DEFAULT'
`

func (q *Queries) DeleteOldDefaultCronTriggersForWorkflowVersion(ctx context.Context, db DBTX, oldworkflowversionid uuid.UUID) error {
	_, err := db.Exec(ctx, deleteOldDefaultCronTriggersForWorkflowVersion, oldworkflowversionid)
	return err
}

const getLatestWorkflowVersionForWorkflows = `-- name: GetLatestWorkflowVersionForWorkflows :many
SELECT DISTINCT ON (wv."workflowId")
    wv."id"
FROM "WorkflowVersion" wv
INNER JOIN "Workflow" w ON w."id" = wv."workflowId"
WHERE
    w."tenantId" = $1::uuid AND
    wv."workflowId" = ANY($2::uuid[]) AND
    w."deletedAt" IS NULL AND
    wv."deletedAt" IS NULL
ORDER BY
    wv."workflowId",
    wv."order" DESC
`

type GetLatestWorkflowVersionForWorkflowsParams struct {
	Tenantid    uuid.UUID   `json:"tenantid"`
	Workflowids []uuid.UUID `json:"workflowids"`
}

func (q *Queries) GetLatestWorkflowVersionForWorkflows(ctx context.Context, db DBTX, arg GetLatestWorkflowVersionForWorkflowsParams) ([]uuid.UUID, error) {
	rows, err := db.Query(ctx, getLatestWorkflowVersionForWorkflows, arg.Tenantid, arg.Workflowids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []uuid.UUID
	for rows.Next() {
		var id uuid.UUID
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getStepsForJobs = `-- name: GetStepsForJobs :many
SELECT
	j."id" as "jobId",
    s.id, s."createdAt", s."updatedAt", s."deletedAt", s."readableId", s."tenantId", s."jobId", s."actionId", s.timeout, s."customUserData", s.retries, s."retryBackoffFactor", s."retryMaxBackoff", s."scheduleTimeout", s."isDurable",
    (
        SELECT array_agg(so."A")::uuid[]  -- Casting the array_agg result to uuid[]
        FROM "_StepOrder" so
        WHERE so."B" = s."id"
    ) AS "parents"
FROM "Job" j
JOIN "Step" s ON s."jobId" = j."id"
WHERE
    j."id" = ANY($1::uuid[])
    AND j."tenantId" = $2::uuid
    AND j."deletedAt" IS NULL
`

type GetStepsForJobsParams struct {
	Jobids   []uuid.UUID `json:"jobids"`
	Tenantid uuid.UUID   `json:"tenantid"`
}

type GetStepsForJobsRow struct {
	JobId   uuid.UUID   `json:"jobId"`
	Step    Step        `json:"step"`
	Parents []uuid.UUID `json:"parents"`
}

func (q *Queries) GetStepsForJobs(ctx context.Context, db DBTX, arg GetStepsForJobsParams) ([]*GetStepsForJobsRow, error) {
	rows, err := db.Query(ctx, getStepsForJobs, arg.Jobids, arg.Tenantid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*GetStepsForJobsRow
	for rows.Next() {
		var i GetStepsForJobsRow
		if err := rows.Scan(
			&i.JobId,
			&i.Step.ID,
			&i.Step.CreatedAt,
			&i.Step.UpdatedAt,
			&i.Step.DeletedAt,
			&i.Step.ReadableId,
			&i.Step.TenantId,
			&i.Step.JobId,
			&i.Step.ActionId,
			&i.Step.Timeout,
			&i.Step.CustomUserData,
			&i.Step.Retries,
			&i.Step.RetryBackoffFactor,
			&i.Step.RetryMaxBackoff,
			&i.Step.ScheduleTimeout,
			&i.Step.IsDurable,
			&i.Parents,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getWorkflowById = `-- name: GetWorkflowById :one
SELECT
    w.id, w."createdAt", w."updatedAt", w."deletedAt", w."tenantId", w.name, w.description, w."isPaused",
    wv."id" as "workflowVersionId"
FROM
    "Workflow" as w
LEFT JOIN "WorkflowVersion" as wv ON w."id" = wv."workflowId"
WHERE
    w."id" = $1::uuid AND
    w."deletedAt" IS NULL
ORDER BY
    wv."order" DESC
LIMIT 1
`

type GetWorkflowByIdRow struct {
	Workflow          Workflow   `json:"workflow"`
	WorkflowVersionId *uuid.UUID `json:"workflowVersionId"`
}

func (q *Queries) GetWorkflowById(ctx context.Context, db DBTX, id uuid.UUID) (*GetWorkflowByIdRow, error) {
	row := db.QueryRow(ctx, getWorkflowById, id)
	var i GetWorkflowByIdRow
	err := row.Scan(
		&i.Workflow.ID,
		&i.Workflow.CreatedAt,
		&i.Workflow.UpdatedAt,
		&i.Workflow.DeletedAt,
		&i.Workflow.TenantId,
		&i.Workflow.Name,
		&i.Workflow.Description,
		&i.Workflow.IsPaused,
		&i.WorkflowVersionId,
	)
	return &i, err
}

const getWorkflowByName = `-- name: GetWorkflowByName :one
SELECT
    id, "createdAt", "updatedAt", "deletedAt", "tenantId", name, description, "isPaused"
FROM
    "Workflow" as workflows
WHERE
    workflows."tenantId" = $1::uuid AND
    workflows."name" = $2::text AND
    workflows."deletedAt" IS NULL
`

type GetWorkflowByNameParams struct {
	Tenantid uuid.UUID `json:"tenantid"`
	Name     string    `json:"name"`
}

func (q *Queries) GetWorkflowByName(ctx context.Context, db DBTX, arg GetWorkflowByNameParams) (*Workflow, error) {
	row := db.QueryRow(ctx, getWorkflowByName, arg.Tenantid, arg.Name)
	var i Workflow
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DeletedAt,
		&i.TenantId,
		&i.Name,
		&i.Description,
		&i.IsPaused,
	)
	return &i, err
}

const getWorkflowLatestVersion = `-- name: GetWorkflowLatestVersion :one
SELECT
    "id"
FROM
    "WorkflowVersion" as workflowVersions
WHERE
    workflowVersions."workflowId" = $1::uuid AND
    workflowVersions."deletedAt" IS NULL
ORDER BY
    workflowVersions."order" DESC
LIMIT 1
`

func (q *Queries) GetWorkflowLatestVersion(ctx context.Context, db DBTX, workflowid uuid.UUID) (uuid.UUID, error) {
	row := db.QueryRow(ctx, getWorkflowLatestVersion, workflowid)
	var id uuid.UUID
	err := row.Scan(&id)
	return id, err
}

const getWorkflowShape = `-- name: GetWorkflowShape :many
SELECT
    s.id AS parentStepId,
    s."readableId" AS stepName,
    array_remove(ARRAY_AGG(so."B"), NULL)::uuid[] AS childrenStepIds
FROM "WorkflowVersion" v
JOIN "Job" j ON v."id" = j."workflowVersionId"
JOIN "Step" s ON j."id" = s."jobId"
LEFT JOIN "_StepOrder" so ON so."A" = s.id
WHERE v.id = $1::uuid
GROUP BY s.id, s."readableId"
`

type GetWorkflowShapeRow struct {
	Parentstepid    uuid.UUID   `json:"parentstepid"`
	Stepname        pgtype.Text `json:"stepname"`
	Childrenstepids []uuid.UUID `json:"childrenstepids"`
}

func (q *Queries) GetWorkflowShape(ctx context.Context, db DBTX, workflowversionid uuid.UUID) ([]*GetWorkflowShapeRow, error) {
	rows, err := db.Query(ctx, getWorkflowShape, workflowversionid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*GetWorkflowShapeRow
	for rows.Next() {
		var i GetWorkflowShapeRow
		if err := rows.Scan(&i.Parentstepid, &i.Stepname, &i.Childrenstepids); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getWorkflowVersionById = `-- name: GetWorkflowVersionById :one
SELECT
    wv.id, wv."createdAt", wv."updatedAt", wv."deletedAt", wv.version, wv."order", wv."workflowId", wv.checksum, wv."scheduleTimeout", wv."onFailureJobId", wv.sticky, wv.kind, wv."defaultPriority", wv."createWorkflowVersionOpts", wv."inputJsonSchema",
    w.id, w."createdAt", w."updatedAt", w."deletedAt", w."tenantId", w.name, w.description, w."isPaused"
FROM
    "WorkflowVersion" as wv
JOIN "Workflow" as w on w."id" = wv."workflowId"
WHERE
    wv."id" = $1::uuid AND
    wv."deletedAt" IS NULL
LIMIT 1
`

type GetWorkflowVersionByIdRow struct {
	WorkflowVersion WorkflowVersion `json:"workflow_version"`
	Workflow        Workflow        `json:"workflow"`
}

func (q *Queries) GetWorkflowVersionById(ctx context.Context, db DBTX, id uuid.UUID) (*GetWorkflowVersionByIdRow, error) {
	row := db.QueryRow(ctx, getWorkflowVersionById, id)
	var i GetWorkflowVersionByIdRow
	err := row.Scan(
		&i.WorkflowVersion.ID,
		&i.WorkflowVersion.CreatedAt,
		&i.WorkflowVersion.UpdatedAt,
		&i.WorkflowVersion.DeletedAt,
		&i.WorkflowVersion.Version,
		&i.WorkflowVersion.Order,
		&i.WorkflowVersion.WorkflowId,
		&i.WorkflowVersion.Checksum,
		&i.WorkflowVersion.ScheduleTimeout,
		&i.WorkflowVersion.OnFailureJobId,
		&i.WorkflowVersion.Sticky,
		&i.WorkflowVersion.Kind,
		&i.WorkflowVersion.DefaultPriority,
		&i.WorkflowVersion.CreateWorkflowVersionOpts,
		&i.WorkflowVersion.InputJsonSchema,
		&i.Workflow.ID,
		&i.Workflow.CreatedAt,
		&i.Workflow.UpdatedAt,
		&i.Workflow.DeletedAt,
		&i.Workflow.TenantId,
		&i.Workflow.Name,
		&i.Workflow.Description,
		&i.Workflow.IsPaused,
	)
	return &i, err
}

const getWorkflowVersionCronTriggerRefs = `-- name: GetWorkflowVersionCronTriggerRefs :many
SELECT
    wtc."parentId", wtc.cron, wtc."tickerId", wtc.input, wtc.enabled, wtc."additionalMetadata", wtc."createdAt", wtc."deletedAt", wtc."updatedAt", wtc.name, wtc.id, wtc.method, wtc.priority
FROM
    "WorkflowTriggerCronRef" as wtc
JOIN "WorkflowTriggers" as wt ON wt."id" = wtc."parentId"
WHERE
    wt."workflowVersionId" = $1::uuid
`

func (q *Queries) GetWorkflowVersionCronTriggerRefs(ctx context.Context, db DBTX, workflowversionid uuid.UUID) ([]*WorkflowTriggerCronRef, error) {
	rows, err := db.Query(ctx, getWorkflowVersionCronTriggerRefs, workflowversionid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*WorkflowTriggerCronRef
	for rows.Next() {
		var i WorkflowTriggerCronRef
		if err := rows.Scan(
			&i.ParentId,
			&i.Cron,
			&i.TickerId,
			&i.Input,
			&i.Enabled,
			&i.AdditionalMetadata,
			&i.CreatedAt,
			&i.DeletedAt,
			&i.UpdatedAt,
			&i.Name,
			&i.ID,
			&i.Method,
			&i.Priority,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getWorkflowVersionEventTriggerRefs = `-- name: GetWorkflowVersionEventTriggerRefs :many
SELECT
    wtc."parentId", wtc."eventKey"
FROM
    "WorkflowTriggerEventRef" as wtc
JOIN "WorkflowTriggers" as wt ON wt."id" = wtc."parentId"
WHERE
    wt."workflowVersionId" = $1::uuid
`

func (q *Queries) GetWorkflowVersionEventTriggerRefs(ctx context.Context, db DBTX, workflowversionid uuid.UUID) ([]*WorkflowTriggerEventRef, error) {
	rows, err := db.Query(ctx, getWorkflowVersionEventTriggerRefs, workflowversionid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*WorkflowTriggerEventRef
	for rows.Next() {
		var i WorkflowTriggerEventRef
		if err := rows.Scan(&i.ParentId, &i.EventKey); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getWorkflowVersionForEngine = `-- name: GetWorkflowVersionForEngine :many
SELECT
    workflowversions.id, workflowversions."createdAt", workflowversions."updatedAt", workflowversions."deletedAt", workflowversions.version, workflowversions."order", workflowversions."workflowId", workflowversions.checksum, workflowversions."scheduleTimeout", workflowversions."onFailureJobId", workflowversions.sticky, workflowversions.kind, workflowversions."defaultPriority", workflowversions."createWorkflowVersionOpts", workflowversions."inputJsonSchema",
    w."name" as "workflowName",
    wc."limitStrategy" as "concurrencyLimitStrategy",
    wc."maxRuns" as "concurrencyMaxRuns",
    wc."getConcurrencyGroupId" as "concurrencyGroupId",
    wc."concurrencyGroupExpression" as "concurrencyGroupExpression"
FROM
    "WorkflowVersion" as workflowVersions
JOIN
    "Workflow" as w ON w."id" = workflowVersions."workflowId"
LEFT JOIN
    "WorkflowConcurrency" as wc ON wc."workflowVersionId" = workflowVersions."id"
WHERE
    workflowVersions."id" = ANY($1::uuid[]) AND
    w."tenantId" = $2::uuid AND
    w."deletedAt" IS NULL AND
    workflowVersions."deletedAt" IS NULL
`

type GetWorkflowVersionForEngineParams struct {
	Ids      []uuid.UUID `json:"ids"`
	Tenantid uuid.UUID   `json:"tenantid"`
}

type GetWorkflowVersionForEngineRow struct {
	WorkflowVersion            WorkflowVersion              `json:"workflow_version"`
	WorkflowName               string                       `json:"workflowName"`
	ConcurrencyLimitStrategy   NullConcurrencyLimitStrategy `json:"concurrencyLimitStrategy"`
	ConcurrencyMaxRuns         pgtype.Int4                  `json:"concurrencyMaxRuns"`
	ConcurrencyGroupId         *uuid.UUID                   `json:"concurrencyGroupId"`
	ConcurrencyGroupExpression pgtype.Text                  `json:"concurrencyGroupExpression"`
}

func (q *Queries) GetWorkflowVersionForEngine(ctx context.Context, db DBTX, arg GetWorkflowVersionForEngineParams) ([]*GetWorkflowVersionForEngineRow, error) {
	rows, err := db.Query(ctx, getWorkflowVersionForEngine, arg.Ids, arg.Tenantid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*GetWorkflowVersionForEngineRow
	for rows.Next() {
		var i GetWorkflowVersionForEngineRow
		if err := rows.Scan(
			&i.WorkflowVersion.ID,
			&i.WorkflowVersion.CreatedAt,
			&i.WorkflowVersion.UpdatedAt,
			&i.WorkflowVersion.DeletedAt,
			&i.WorkflowVersion.Version,
			&i.WorkflowVersion.Order,
			&i.WorkflowVersion.WorkflowId,
			&i.WorkflowVersion.Checksum,
			&i.WorkflowVersion.ScheduleTimeout,
			&i.WorkflowVersion.OnFailureJobId,
			&i.WorkflowVersion.Sticky,
			&i.WorkflowVersion.Kind,
			&i.WorkflowVersion.DefaultPriority,
			&i.WorkflowVersion.CreateWorkflowVersionOpts,
			&i.WorkflowVersion.InputJsonSchema,
			&i.WorkflowName,
			&i.ConcurrencyLimitStrategy,
			&i.ConcurrencyMaxRuns,
			&i.ConcurrencyGroupId,
			&i.ConcurrencyGroupExpression,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const getWorkflowVersionScheduleTriggerRefs = `-- name: GetWorkflowVersionScheduleTriggerRefs :many
SELECT
    wtc.id, wtc."parentId", wtc."triggerAt", wtc."tickerId", wtc.input, wtc."childIndex", wtc."childKey", wtc."parentStepRunId", wtc."parentWorkflowRunId", wtc."additionalMetadata", wtc."createdAt", wtc."deletedAt", wtc."updatedAt", wtc.method, wtc.priority
FROM
    "WorkflowTriggerScheduledRef" as wtc
JOIN "WorkflowTriggers" as wt ON wt."id" = wtc."parentId"
WHERE
    wt."workflowVersionId" = $1::uuid
`

func (q *Queries) GetWorkflowVersionScheduleTriggerRefs(ctx context.Context, db DBTX, workflowversionid uuid.UUID) ([]*WorkflowTriggerScheduledRef, error) {
	rows, err := db.Query(ctx, getWorkflowVersionScheduleTriggerRefs, workflowversionid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*WorkflowTriggerScheduledRef
	for rows.Next() {
		var i WorkflowTriggerScheduledRef
		if err := rows.Scan(
			&i.ID,
			&i.ParentId,
			&i.TriggerAt,
			&i.TickerId,
			&i.Input,
			&i.ChildIndex,
			&i.ChildKey,
			&i.ParentStepRunId,
			&i.ParentWorkflowRunId,
			&i.AdditionalMetadata,
			&i.CreatedAt,
			&i.DeletedAt,
			&i.UpdatedAt,
			&i.Method,
			&i.Priority,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const linkOnFailureJob = `-- name: LinkOnFailureJob :one
UPDATE "WorkflowVersion"
SET "onFailureJobId" = $1::uuid
WHERE "id" = $2::uuid
RETURNING id, "createdAt", "updatedAt", "deletedAt", version, "order", "workflowId", checksum, "scheduleTimeout", "onFailureJobId", sticky, kind, "defaultPriority", "createWorkflowVersionOpts", "inputJsonSchema"
`

type LinkOnFailureJobParams struct {
	Jobid             uuid.UUID `json:"jobid"`
	Workflowversionid uuid.UUID `json:"workflowversionid"`
}

func (q *Queries) LinkOnFailureJob(ctx context.Context, db DBTX, arg LinkOnFailureJobParams) (*WorkflowVersion, error) {
	row := db.QueryRow(ctx, linkOnFailureJob, arg.Jobid, arg.Workflowversionid)
	var i WorkflowVersion
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DeletedAt,
		&i.Version,
		&i.Order,
		&i.WorkflowId,
		&i.Checksum,
		&i.ScheduleTimeout,
		&i.OnFailureJobId,
		&i.Sticky,
		&i.Kind,
		&i.DefaultPriority,
		&i.CreateWorkflowVersionOpts,
		&i.InputJsonSchema,
	)
	return &i, err
}

const listStepExpressions = `-- name: ListStepExpressions :many
SELECT
    key, "stepId", expression, kind
FROM
    "StepExpression"
WHERE
    "stepId" = ANY($1::uuid[])
`

func (q *Queries) ListStepExpressions(ctx context.Context, db DBTX, stepids []uuid.UUID) ([]*StepExpression, error) {
	rows, err := db.Query(ctx, listStepExpressions, stepids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*StepExpression
	for rows.Next() {
		var i StepExpression
		if err := rows.Scan(
			&i.Key,
			&i.StepId,
			&i.Expression,
			&i.Kind,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listStepMatchConditions = `-- name: ListStepMatchConditions :many
SELECT
    id, tenant_id, step_id, readable_data_key, action, or_group_id, expression, kind, sleep_duration, event_key, parent_readable_id
FROM
    v1_step_match_condition
WHERE
    step_id = ANY($1::uuid[])
    AND tenant_id = $2::uuid
`

type ListStepMatchConditionsParams struct {
	Stepids  []uuid.UUID `json:"stepids"`
	Tenantid uuid.UUID   `json:"tenantid"`
}

func (q *Queries) ListStepMatchConditions(ctx context.Context, db DBTX, arg ListStepMatchConditionsParams) ([]*V1StepMatchCondition, error) {
	rows, err := db.Query(ctx, listStepMatchConditions, arg.Stepids, arg.Tenantid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*V1StepMatchCondition
	for rows.Next() {
		var i V1StepMatchCondition
		if err := rows.Scan(
			&i.ID,
			&i.TenantID,
			&i.StepID,
			&i.ReadableDataKey,
			&i.Action,
			&i.OrGroupID,
			&i.Expression,
			&i.Kind,
			&i.SleepDuration,
			&i.EventKey,
			&i.ParentReadableID,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listStepsByIds = `-- name: ListStepsByIds :many
SELECT
    s.id, s."createdAt", s."updatedAt", s."deletedAt", s."readableId", s."tenantId", s."jobId", s."actionId", s.timeout, s."customUserData", s.retries, s."retryBackoffFactor", s."retryMaxBackoff", s."scheduleTimeout", s."isDurable",
    wv."id" as "workflowVersionId",
    wv."sticky" as "workflowVersionSticky",
    w."name" as "workflowName",
    w."id" as "workflowId",
    COALESCE(wv."defaultPriority", 1) AS "defaultPriority",
    COUNT(se."stepId") as "exprCount",
    COUNT(sc.id) as "concurrencyCount"
FROM
    "Step" s
JOIN
    "Job" j ON j."id" = s."jobId"
JOIN
    "WorkflowVersion" wv ON wv."id" = j."workflowVersionId"
JOIN
    "Workflow" w ON w."id" = wv."workflowId"
LEFT JOIN
    v1_step_concurrency sc ON sc.workflow_id = w."id" AND sc.step_id = s."id"
LEFT JOIN
    "StepExpression" se ON se."stepId" = s."id"
WHERE
    s."id" = ANY($1::uuid[])
    AND w."tenantId" = $2::uuid
    AND w."deletedAt" IS NULL
    AND wv."deletedAt" IS NULL
GROUP BY
    s."id", wv."id", w."name", w."id", wv."sticky"
`

type ListStepsByIdsParams struct {
	Ids      []uuid.UUID `json:"ids"`
	Tenantid uuid.UUID   `json:"tenantid"`
}

type ListStepsByIdsRow struct {
	ID                    uuid.UUID          `json:"id"`
	CreatedAt             pgtype.Timestamp   `json:"createdAt"`
	UpdatedAt             pgtype.Timestamp   `json:"updatedAt"`
	DeletedAt             pgtype.Timestamp   `json:"deletedAt"`
	ReadableId            pgtype.Text        `json:"readableId"`
	TenantId              uuid.UUID          `json:"tenantId"`
	JobId                 uuid.UUID          `json:"jobId"`
	ActionId              string             `json:"actionId"`
	Timeout               pgtype.Text        `json:"timeout"`
	CustomUserData        []byte             `json:"customUserData"`
	Retries               int32              `json:"retries"`
	RetryBackoffFactor    pgtype.Float8      `json:"retryBackoffFactor"`
	RetryMaxBackoff       pgtype.Int4        `json:"retryMaxBackoff"`
	ScheduleTimeout       string             `json:"scheduleTimeout"`
	IsDurable             bool               `json:"isDurable"`
	WorkflowVersionId     uuid.UUID          `json:"workflowVersionId"`
	WorkflowVersionSticky NullStickyStrategy `json:"workflowVersionSticky"`
	WorkflowName          string             `json:"workflowName"`
	WorkflowId            uuid.UUID          `json:"workflowId"`
	DefaultPriority       int32              `json:"defaultPriority"`
	ExprCount             int64              `json:"exprCount"`
	ConcurrencyCount      int64              `json:"concurrencyCount"`
}

func (q *Queries) ListStepsByIds(ctx context.Context, db DBTX, arg ListStepsByIdsParams) ([]*ListStepsByIdsRow, error) {
	rows, err := db.Query(ctx, listStepsByIds, arg.Ids, arg.Tenantid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*ListStepsByIdsRow
	for rows.Next() {
		var i ListStepsByIdsRow
		if err := rows.Scan(
			&i.ID,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.DeletedAt,
			&i.ReadableId,
			&i.TenantId,
			&i.JobId,
			&i.ActionId,
			&i.Timeout,
			&i.CustomUserData,
			&i.Retries,
			&i.RetryBackoffFactor,
			&i.RetryMaxBackoff,
			&i.ScheduleTimeout,
			&i.IsDurable,
			&i.WorkflowVersionId,
			&i.WorkflowVersionSticky,
			&i.WorkflowName,
			&i.WorkflowId,
			&i.DefaultPriority,
			&i.ExprCount,
			&i.ConcurrencyCount,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listStepsByWorkflowVersionIds = `-- name: ListStepsByWorkflowVersionIds :many
WITH steps AS (
    SELECT
        s.id, s."createdAt", s."updatedAt", s."deletedAt", s."readableId", s."tenantId", s."jobId", s."actionId", s.timeout, s."customUserData", s.retries, s."retryBackoffFactor", s."retryMaxBackoff", s."scheduleTimeout", s."isDurable",
        wv."id" as "workflowVersionId",
        w."name" as "workflowName",
        w."id" as "workflowId",
        j."kind" as "jobKind",
        COUNT(mc.id) as "matchConditionCount"
    FROM
        "WorkflowVersion" as wv
    JOIN
        "Workflow" as w ON w."id" = wv."workflowId"
    JOIN
        "Job" j ON j."workflowVersionId" = wv."id"
    JOIN
        "Step" s ON s."jobId" = j."id"
    LEFT JOIN
        v1_step_match_condition mc ON mc.step_id = s."id"
    WHERE
        wv."id" = ANY($1::uuid[])
        AND w."tenantId" = $2::uuid
        AND w."deletedAt" IS NULL
        AND wv."deletedAt" IS NULL
    GROUP BY
        s."id", wv."id", w."name", w."id", j."kind"
), step_orders AS (
    SELECT
        so."B" as "stepId",
        array_agg(so."A")::uuid[] as "parents"
    FROM
        steps
    JOIN
        "_StepOrder" so ON so."B" = steps."id"
    GROUP BY
        so."B"
)
SELECT
    s.id, s."createdAt", s."updatedAt", s."deletedAt", s."readableId", s."tenantId", s."jobId", s."actionId", s.timeout, s."customUserData", s.retries, s."retryBackoffFactor", s."retryMaxBackoff", s."scheduleTimeout", s."isDurable", s."workflowVersionId", s."workflowName", s."workflowId", s."jobKind", s."matchConditionCount",
    COALESCE(so."parents", '{}'::uuid[]) as "parents"
FROM
    steps s
LEFT JOIN
    step_orders so ON so."stepId" = s."id"
`

type ListStepsByWorkflowVersionIdsParams struct {
	Ids      []uuid.UUID `json:"ids"`
	Tenantid uuid.UUID   `json:"tenantid"`
}

type ListStepsByWorkflowVersionIdsRow struct {
	ID                  uuid.UUID        `json:"id"`
	CreatedAt           pgtype.Timestamp `json:"createdAt"`
	UpdatedAt           pgtype.Timestamp `json:"updatedAt"`
	DeletedAt           pgtype.Timestamp `json:"deletedAt"`
	ReadableId          pgtype.Text      `json:"readableId"`
	TenantId            uuid.UUID        `json:"tenantId"`
	JobId               uuid.UUID        `json:"jobId"`
	ActionId            string           `json:"actionId"`
	Timeout             pgtype.Text      `json:"timeout"`
	CustomUserData      []byte           `json:"customUserData"`
	Retries             int32            `json:"retries"`
	RetryBackoffFactor  pgtype.Float8    `json:"retryBackoffFactor"`
	RetryMaxBackoff     pgtype.Int4      `json:"retryMaxBackoff"`
	ScheduleTimeout     string           `json:"scheduleTimeout"`
	IsDurable           bool             `json:"isDurable"`
	WorkflowVersionId   uuid.UUID        `json:"workflowVersionId"`
	WorkflowName        string           `json:"workflowName"`
	WorkflowId          uuid.UUID        `json:"workflowId"`
	JobKind             JobKind          `json:"jobKind"`
	MatchConditionCount int64            `json:"matchConditionCount"`
	Parents             []uuid.UUID      `json:"parents"`
}

func (q *Queries) ListStepsByWorkflowVersionIds(ctx context.Context, db DBTX, arg ListStepsByWorkflowVersionIdsParams) ([]*ListStepsByWorkflowVersionIdsRow, error) {
	rows, err := db.Query(ctx, listStepsByWorkflowVersionIds, arg.Ids, arg.Tenantid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*ListStepsByWorkflowVersionIdsRow
	for rows.Next() {
		var i ListStepsByWorkflowVersionIdsRow
		if err := rows.Scan(
			&i.ID,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.DeletedAt,
			&i.ReadableId,
			&i.TenantId,
			&i.JobId,
			&i.ActionId,
			&i.Timeout,
			&i.CustomUserData,
			&i.Retries,
			&i.RetryBackoffFactor,
			&i.RetryMaxBackoff,
			&i.ScheduleTimeout,
			&i.IsDurable,
			&i.WorkflowVersionId,
			&i.WorkflowName,
			&i.WorkflowId,
			&i.JobKind,
			&i.MatchConditionCount,
			&i.Parents,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowConcurrencyByVersionId = `-- name: ListWorkflowConcurrencyByVersionId :many
SELECT
    wc.id,
    wc.max_concurrency AS "maxRuns",
    wc.strategy AS "limitStrategy",
    wc.expression
FROM
    v1_workflow_concurrency wc
WHERE
    wc.workflow_version_id = $1::uuid AND
    wc.workflow_id = $2::uuid
ORDER BY wc.id ASC
`

type ListWorkflowConcurrencyByVersionIdParams struct {
	Workflowversionid uuid.UUID `json:"workflowversionid"`
	Workflowid        uuid.UUID `json:"workflowid"`
}

type ListWorkflowConcurrencyByVersionIdRow struct {
	ID            int64                 `json:"id"`
	MaxRuns       int32                 `json:"maxRuns"`
	LimitStrategy V1ConcurrencyStrategy `json:"limitStrategy"`
	Expression    string                `json:"expression"`
}

func (q *Queries) ListWorkflowConcurrencyByVersionId(ctx context.Context, db DBTX, arg ListWorkflowConcurrencyByVersionIdParams) ([]*ListWorkflowConcurrencyByVersionIdRow, error) {
	rows, err := db.Query(ctx, listWorkflowConcurrencyByVersionId, arg.Workflowversionid, arg.Workflowid)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*ListWorkflowConcurrencyByVersionIdRow
	for rows.Next() {
		var i ListWorkflowConcurrencyByVersionIdRow
		if err := rows.Scan(
			&i.ID,
			&i.MaxRuns,
			&i.LimitStrategy,
			&i.Expression,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflowNamesByIds = `-- name: ListWorkflowNamesByIds :many
SELECT id, name
FROM "Workflow"
WHERE id = ANY($1::uuid[])
`

type ListWorkflowNamesByIdsRow struct {
	ID   uuid.UUID `json:"id"`
	Name string    `json:"name"`
}

func (q *Queries) ListWorkflowNamesByIds(ctx context.Context, db DBTX, ids []uuid.UUID) ([]*ListWorkflowNamesByIdsRow, error) {
	rows, err := db.Query(ctx, listWorkflowNamesByIds, ids)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*ListWorkflowNamesByIdsRow
	for rows.Next() {
		var i ListWorkflowNamesByIdsRow
		if err := rows.Scan(&i.ID, &i.Name); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listWorkflows = `-- name: ListWorkflows :many
SELECT
    workflows.id, workflows."createdAt", workflows."updatedAt", workflows."deletedAt", workflows."tenantId", workflows.name, workflows.description, workflows."isPaused"
FROM
    "Workflow" as workflows
WHERE
    workflows."tenantId" = $1::uuid AND
    workflows."deletedAt" IS NULL AND
    (
        $2::text IS NULL OR
        workflows.name iLIKE concat('%', $2::TEXT, '%')
    )
ORDER BY
    case when $3 = 'createdAt ASC' THEN workflows."createdAt" END ASC ,
    case when $3 = 'createdAt DESC' then workflows."createdAt" END DESC
OFFSET
    COALESCE($4, 0)
LIMIT
    COALESCE($5, 50)
`

type ListWorkflowsParams struct {
	Tenantid uuid.UUID   `json:"tenantid"`
	Search   pgtype.Text `json:"search"`
	Orderby  interface{} `json:"orderby"`
	Offset   interface{} `json:"offset"`
	Limit    interface{} `json:"limit"`
}

type ListWorkflowsRow struct {
	Workflow Workflow `json:"workflow"`
}

func (q *Queries) ListWorkflows(ctx context.Context, db DBTX, arg ListWorkflowsParams) ([]*ListWorkflowsRow, error) {
	rows, err := db.Query(ctx, listWorkflows,
		arg.Tenantid,
		arg.Search,
		arg.Orderby,
		arg.Offset,
		arg.Limit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []*ListWorkflowsRow
	for rows.Next() {
		var i ListWorkflowsRow
		if err := rows.Scan(
			&i.Workflow.ID,
			&i.Workflow.CreatedAt,
			&i.Workflow.UpdatedAt,
			&i.Workflow.DeletedAt,
			&i.Workflow.TenantId,
			&i.Workflow.Name,
			&i.Workflow.Description,
			&i.Workflow.IsPaused,
		); err != nil {
			return nil, err
		}
		items = append(items, &i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lockWorkflowVersion = `-- name: LockWorkflowVersion :one
SELECT
    "id"
FROM
    "WorkflowVersion"
WHERE
    "workflowId" = $1::uuid AND
    "deletedAt" IS NULL
ORDER BY
    "order" DESC
LIMIT 1
FOR UPDATE
`

func (q *Queries) LockWorkflowVersion(ctx context.Context, db DBTX, workflowid uuid.UUID) (uuid.UUID, error) {
	row := db.QueryRow(ctx, lockWorkflowVersion, workflowid)
	var id uuid.UUID
	err := row.Scan(&id)
	return id, err
}

const moveCronTriggerToNewWorkflowTriggers = `-- name: MoveCronTriggerToNewWorkflowTriggers :exec
WITH triggersToUpdate AS (
    SELECT
        cronTrigger."id",
        cronTrigger."enabled"
    FROM "WorkflowTriggerCronRef" cronTrigger
    JOIN "WorkflowTriggers" triggers ON triggers."id" = cronTrigger."parentId"
    WHERE triggers."workflowVersionId" = $2::uuid
    AND cronTrigger."method" = 'API'
)
UPDATE "WorkflowTriggerCronRef"
SET
    "parentId" = $1::uuid,
    "enabled" = triggersToUpdate."enabled"
FROM triggersToUpdate
WHERE "WorkflowTriggerCronRef"."id" = triggersToUpdate."id"
`

type MoveCronTriggerToNewWorkflowTriggersParams struct {
	Newworkflowtriggerid uuid.UUID `json:"newworkflowtriggerid"`
	Oldworkflowversionid uuid.UUID `json:"oldworkflowversionid"`
}

func (q *Queries) MoveCronTriggerToNewWorkflowTriggers(ctx context.Context, db DBTX, arg MoveCronTriggerToNewWorkflowTriggersParams) error {
	_, err := db.Exec(ctx, moveCronTriggerToNewWorkflowTriggers, arg.Newworkflowtriggerid, arg.Oldworkflowversionid)
	return err
}

const moveScheduledTriggerToNewWorkflowTriggers = `-- name: MoveScheduledTriggerToNewWorkflowTriggers :exec
WITH triggersToUpdate AS (
    SELECT scheduledTrigger."id" FROM "WorkflowTriggerScheduledRef" scheduledTrigger
    JOIN "WorkflowTriggers" triggers ON triggers."id" = scheduledTrigger."parentId"
    WHERE triggers."workflowVersionId" = $2::uuid
    AND scheduledTrigger."method" = 'API'
)
UPDATE "WorkflowTriggerScheduledRef"
SET "parentId" = $1::uuid
WHERE "id" IN (SELECT "id" FROM triggersToUpdate)
`

type MoveScheduledTriggerToNewWorkflowTriggersParams struct {
	Newworkflowtriggerid uuid.UUID `json:"newworkflowtriggerid"`
	Oldworkflowversionid uuid.UUID `json:"oldworkflowversionid"`
}

func (q *Queries) MoveScheduledTriggerToNewWorkflowTriggers(ctx context.Context, db DBTX, arg MoveScheduledTriggerToNewWorkflowTriggersParams) error {
	_, err := db.Exec(ctx, moveScheduledTriggerToNewWorkflowTriggers, arg.Newworkflowtriggerid, arg.Oldworkflowversionid)
	return err
}

const softDeleteWorkflow = `-- name: SoftDeleteWorkflow :one
WITH versions AS (
    UPDATE "WorkflowVersion"
    SET "deletedAt" = CURRENT_TIMESTAMP
    WHERE "workflowId" = $1::uuid
)
UPDATE "Workflow"
SET
    -- set name to the current name plus a random suffix to avoid conflicts
    "name" = "name" || '-' || gen_random_uuid(),
    "deletedAt" = CURRENT_TIMESTAMP
WHERE "id" = $1::uuid
RETURNING id, "createdAt", "updatedAt", "deletedAt", "tenantId", name, description, "isPaused"
`

func (q *Queries) SoftDeleteWorkflow(ctx context.Context, db DBTX, id uuid.UUID) (*Workflow, error) {
	row := db.QueryRow(ctx, softDeleteWorkflow, id)
	var i Workflow
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DeletedAt,
		&i.TenantId,
		&i.Name,
		&i.Description,
		&i.IsPaused,
	)
	return &i, err
}

const updateCronTrigger = `-- name: UpdateCronTrigger :exec
UPDATE "WorkflowTriggerCronRef"
SET
    "enabled" = COALESCE($1::BOOLEAN, "enabled")
WHERE "id" = $2::uuid
`

type UpdateCronTriggerParams struct {
	Enabled       pgtype.Bool `json:"enabled"`
	Crontriggerid uuid.UUID   `json:"crontriggerid"`
}

func (q *Queries) UpdateCronTrigger(ctx context.Context, db DBTX, arg UpdateCronTriggerParams) error {
	_, err := db.Exec(ctx, updateCronTrigger, arg.Enabled, arg.Crontriggerid)
	return err
}

const updateWorkflow = `-- name: UpdateWorkflow :one
UPDATE "Workflow"
SET
    "updatedAt" = CURRENT_TIMESTAMP,
    "isPaused" = coalesce($1::boolean, "isPaused")
WHERE "id" = $2::uuid
RETURNING id, "createdAt", "updatedAt", "deletedAt", "tenantId", name, description, "isPaused"
`

type UpdateWorkflowParams struct {
	IsPaused pgtype.Bool `json:"isPaused"`
	ID       uuid.UUID   `json:"id"`
}

func (q *Queries) UpdateWorkflow(ctx context.Context, db DBTX, arg UpdateWorkflowParams) (*Workflow, error) {
	row := db.QueryRow(ctx, updateWorkflow, arg.IsPaused, arg.ID)
	var i Workflow
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.DeletedAt,
		&i.TenantId,
		&i.Name,
		&i.Description,
		&i.IsPaused,
	)
	return &i, err
}

const updateWorkflowConcurrencyWithChildStrategyIds = `-- name: UpdateWorkflowConcurrencyWithChildStrategyIds :exec
UPDATE v1_workflow_concurrency
SET child_strategy_ids = $1::bigint[]
WHERE workflow_id = $2::uuid
  AND workflow_version_id = $3::uuid
  AND id = $4::bigint
`

type UpdateWorkflowConcurrencyWithChildStrategyIdsParams struct {
	Childstrategyids      []int64   `json:"childstrategyids"`
	Workflowid            uuid.UUID `json:"workflowid"`
	Workflowversionid     uuid.UUID `json:"workflowversionid"`
	Workflowconcurrencyid int64     `json:"workflowconcurrencyid"`
}

// Update the workflow concurrency row using its primary key.
func (q *Queries) UpdateWorkflowConcurrencyWithChildStrategyIds(ctx context.Context, db DBTX, arg UpdateWorkflowConcurrencyWithChildStrategyIdsParams) error {
	_, err := db.Exec(ctx, updateWorkflowConcurrencyWithChildStrategyIds,
		arg.Childstrategyids,
		arg.Workflowid,
		arg.Workflowversionid,
		arg.Workflowconcurrencyid,
	)
	return err
}

const upsertAction = `-- name: UpsertAction :one
INSERT INTO "Action" (
    "id",
    "actionId",
    "tenantId"
)
VALUES (
    gen_random_uuid(),
    LOWER($1::text),
    $2::uuid
)
ON CONFLICT ("tenantId", "actionId") DO UPDATE
SET
    "tenantId" = EXCLUDED."tenantId"
WHERE
    "Action"."tenantId" = $2 AND "Action"."actionId" = LOWER($1::text)
RETURNING description, "tenantId", "actionId", id
`

type UpsertActionParams struct {
	Action   string    `json:"action"`
	Tenantid uuid.UUID `json:"tenantid"`
}

func (q *Queries) UpsertAction(ctx context.Context, db DBTX, arg UpsertActionParams) (*Action, error) {
	row := db.QueryRow(ctx, upsertAction, arg.Action, arg.Tenantid)
	var i Action
	err := row.Scan(
		&i.Description,
		&i.TenantId,
		&i.ActionId,
		&i.ID,
	)
	return &i, err
}

const upsertDesiredWorkerLabel = `-- name: UpsertDesiredWorkerLabel :one
INSERT INTO "StepDesiredWorkerLabel" (
    "createdAt",
    "updatedAt",
    "stepId",
    "key",
    "intValue",
    "strValue",
    "required",
    "weight",
    "comparator"
) VALUES (
    CURRENT_TIMESTAMP,
    CURRENT_TIMESTAMP,
    $1::uuid,
    $2::text,
    COALESCE($3::int, NULL),
    COALESCE($4::text, NULL),
    COALESCE($5::boolean, false),
    COALESCE($6::int, 100),
    COALESCE($7::"WorkerLabelComparator", 'EQUAL')
) ON CONFLICT ("stepId", "key") DO UPDATE
SET
    "updatedAt" = CURRENT_TIMESTAMP,
    "intValue" = COALESCE($3::int, null),
    "strValue" = COALESCE($4::text, null),
    "required" = COALESCE($5::boolean, false),
    "weight" = COALESCE($6::int, 100),
    "comparator" = COALESCE($7::"WorkerLabelComparator", 'EQUAL')
RETURNING id, "createdAt", "updatedAt", "stepId", key, "strValue", "intValue", required, comparator, weight
`

type UpsertDesiredWorkerLabelParams struct {
	Stepid     uuid.UUID                 `json:"stepid"`
	Key        string                    `json:"key"`
	IntValue   pgtype.Int4               `json:"intValue"`
	StrValue   pgtype.Text               `json:"strValue"`
	Required   pgtype.Bool               `json:"required"`
	Weight     pgtype.Int4               `json:"weight"`
	Comparator NullWorkerLabelComparator `json:"comparator"`
}

func (q *Queries) UpsertDesiredWorkerLabel(ctx context.Context, db DBTX, arg UpsertDesiredWorkerLabelParams) (*StepDesiredWorkerLabel, error) {
	row := db.QueryRow(ctx, upsertDesiredWorkerLabel,
		arg.Stepid,
		arg.Key,
		arg.IntValue,
		arg.StrValue,
		arg.Required,
		arg.Weight,
		arg.Comparator,
	)
	var i StepDesiredWorkerLabel
	err := row.Scan(
		&i.ID,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.StepId,
		&i.Key,
		&i.StrValue,
		&i.IntValue,
		&i.Required,
		&i.Comparator,
		&i.Weight,
	)
	return &i, err
}
