#!/bin/bash

# SPDX-FileCopyrightText: 2020 Stefano Zacchiroli <zack@upsilon.cc>
# SPDX-License-Identifier: GPL-3.0-or-later

# Depends: moreutils, zstd

PG_SERVICE="swh-replica"

run_query() {
    queryfile="$1"
    destfile="$2"

    tempfile=$(mktemp)
    trap "rm -f ${tempfile}" EXIT

    echo '\timing' >> "$tempfile"
    echo -n '\copy ( ' >> "$tempfile"
    echo -n $(paste -sd " " "$queryfile") >> "$tempfile"
    echo ") to program 'zstdmt > ${destfile}' with (format csv) ;" >> "$tempfile"

    psql service="$PG_SERVICE" -f "$tempfile" &> ${destfile/.zst/.log}
}

run_query "export_commits.sql" "commits.csv.zst"
run_query "export_authors.sql" "authors.csv.zst"
