-- name: SelectCharacterByID :one
SELECT * FROM data_character WHERE id = @id::text;

-- name: SelectCharacterByNick :one
SELECT * FROM data_character WHERE nicks <@ ARRAY[@nick::text];

-- name: SelectCharacterByName :one
SELECT * FROM data_character WHERE name = @name::text;

-- name: SelectCharacters :many
SELECT * FROM data_character
WHERE (@filter_id::bool = false OR id = ANY(@ids::text[]))
    AND (@filter_name::bool = false OR name = ANY(@names::text[]))
    AND (@filter_nick::bool = false OR nicks && (@nicks::text[]))
    AND (@filter_author::bool = false OR author = @author::text)
    AND (@filter_search::bool = false OR "ts_vector" @@ to_tsquery(@search::text))
LIMIT NULLIF(@limit_size::INT, 0);

-- name: InsertCharacter :exec
INSERT INTO data_character (id, nicks, name, short_name, author, description, ts_vector) VALUES (
    @id::text, @nicks::text[], @name::text,
    @short_name::text, @author::text, @description::text,
    to_tsvector(
        'english', @name::text || ' ' || @description::text || ' ' || @author::text || ' '
        || immutable_array_to_string(@nicks::text[], ' ')
    )
);

-- name: UpdateCharacter :exec
UPDATE data_character
SET name = @name::text,
    short_name = @short_name::text,
    description = @description::text
WHERE id = @id::text;

-- name: AddCharacterNick :exec
UPDATE data_character
SET nicks=array_append(nicks, @nick::text)
WHERE id = @id::text;

-- name: RemoveCharacterNick :exec
UPDATE data_character
SET nicks=array_remove(nicks, @nick::text)
WHERE id = @id::text;

-- name: DeleteCharacter :exec
DELETE FROM data_character WHERE id=$1;