-- name: SetTag :exec
INSERT INTO common_tag (tag, target_kind, target_id)
VALUES (
    sqlc.arg(tag)::TEXT, sqlc.arg(target_kind)::TEXT, sqlc.arg(target_id)::TEXT
)
ON CONFLICT DO NOTHING;

-- name: SetTags :exec
INSERT INTO common_tag (tag, target_kind, target_id)
SELECT unnest(sqlc.arg(tags)::TEXT[]), sqlc.arg(target_kind)::TEXT as target_kind, sqlc.arg(target_id)::TEXT as target_id
ON CONFLICT DO NOTHING;

-- name: ClearTag :exec
DELETE FROM common_tag
WHERE tag=sqlc.arg(tag)::TEXT
  AND target_kind=sqlc.arg(target_kind)::TEXT
  AND target_id=sqlc.arg(target_id)::TEXT;

-- name: ClearTagsByTargetLike :exec
DELETE FROM common_tag
WHERE target_kind=sqlc.arg(target_kind)::TEXT
  AND target_id=sqlc.arg(target_id)::TEXT
  AND tag LIKE sqlc.arg(tag_like)::TEXT;

-- name: ClearTagsByTarget :exec
DELETE FROM common_tag
WHERE target_kind=sqlc.arg(target_kind)::TEXT
  AND target_id=sqlc.arg(target_id)::TEXT;

-- name: SelectDistinctTags :many
SELECT DISTINCT tag FROM common_tag ORDER BY tag;

-- name: SelectDistinctTagsLike :many
SELECT DISTINCT tag FROM common_tag WHERE tag LIKE $1::text ORDER BY tag;

-- name: SelectTagsByTag :many
SELECT * FROM common_tag WHERE tag = sqlc.arg(tag_name)::text ORDER BY tag;

-- name: SelectTagsByTags :many
SELECT * FROM common_tag WHERE tag = ANY(sqlc.arg(tag_names)::text[]) ORDER BY tag;

-- name: SelectTargetsByTags :many
SELECT DISTINCT(target_id) FROM common_tag WHERE tag = ANY(sqlc.arg(tag_names)::text[]) AND target_kind = sqlc.arg(target_kind)::text ORDER BY tag;

-- name: SelectTagsByTarget :many
SELECT * FROM common_tag WHERE target_kind = sqlc.arg(target_kind) AND target_id = sqlc.arg(target_id)::text ORDER BY tag;

-- name: SelectTagsByTargets :many
SELECT * FROM common_tag WHERE target_kind = sqlc.arg(target_kind) AND target_id = ANY(sqlc.arg(target_ids)::text[]) ORDER BY tag;
