# -*- mode: shell-script -*-

##
## Database access helpers (from cyclos/immich pattern in 0k-charms)
##

## Get target service name for a named relation
outline:relation-get-target-service() {
    local relation="$1" ts
    if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "$relation"); then
        err "Couldn't find relation ${DARKCYAN}$relation${NORMAL}."
        return 1
    fi
    e "$ts"
}


## Get the raw data of a named relation
outline:relation-get-config() {
    local relation="$1" ts relation_dir
    ts=$(outline:relation-get-target-service "$relation") || return 1
    relation_dir=$(get_relation_data_dir "$SERVICE_NAME" "$ts" "$relation") || return 1
    cat "${relation_dir}/data"
}


## Get a key from the relation data
outline:named-relation-get() {
    local relation="$1" key="$2" config
    config=$(outline:relation-get-config "$relation") || return 1
    e "$config" | shyaml get-value "$key" || {
        err "Couldn't get ${WHITE}$key${NORMAL} value" \
            "in ${DARKCYAN}$relation${NORMAL} relation's data."
        return 1
    }
}


## Run SQL as the postgres superuser on the database related to this
## service through the "postgres-database" relation.
## Usage: sql < <(echo "SELECT ...")
##        echo "SELECT ..." | sql
sql() {
    (
        local dbname ts target_charm target_charm_path
        dbname="$(outline:named-relation-get "postgres-database" dbname)" || exit 1
        ts=$(outline:relation-get-target-service "postgres-database") || exit 1

        export SERVICE_NAME="$ts"
        export SERVICE_DATASTORE="$DATASTORE/$SERVICE_NAME"
        DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$SERVICE_NAME") || exit 1
        export DOCKER_BASE_IMAGE

        target_charm=$(get_service_charm "$ts") || exit 1
        target_charm_path=$(charm.get_dir "$target_charm") || exit 1

        set +e
        . "$target_charm_path/lib/common"
        set -e

        ensure_db_docker_running

        ddb -d "$dbname" -v ON_ERROR_STOP=1
    )
}
