crowdsec/tests/lib/db/instance-postgres
Manuel Sabban 37756e8082
improve test packaging (#1443)
* improve tests for packaging

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
2022-04-15 15:39:17 +02:00

100 lines
2.2 KiB
Bash
Executable file

#!/usr/bin/env bash
set -eu
script_name=$0
DB_BACKEND=$(echo $script_name | cut -d- -f2)
export DB_BACKEND
die() {
echo >&2 "$@"
exit 1
}
PGHOST=${PGHOST:-127.0.0.1}
PGPORT=${PGPORT:-5432}
PGPASSWORD=${PGPASSWORD:-postgres}
PGUSER=${PGUSER:-postgres}
PGDUMP=${PGDUMP:-pg_dumpall}
PGRESTORE=${PGRESTORE:-psql}
export PGHOST
export PGPORT
export PGPASSWORD
export PGUSER
about() {
die "usage: $script_name [ config_yaml | setup | dump <backup_file> | restore <backup_file> ]"
}
check_postgres_client() {
if ! command -v psql --version >/dev/null; then
die "missing required program 'psql' as a postgres client (package postgres-client-13 on debian like system)"
fi
}
exec_sql() {
cmd="${1?Missing required sql command}"
psql <<< "$cmd"
}
requirements() {
check_mysql_client
}
setup() {
exec_sql "DROP DATABASE IF EXISTS crowdsec_test;"
exec_sql "CREATE DATABASE crowdsec_test;"
exec_sql "DROP USER IF EXISTS crowdsec_test;"
exec_sql "CREATE USER crowdsec_test WITH ENCRYPTED PASSWORD 'crowdsec_test';"
exec_sql "GRANT ALL PRIVILEGES ON DATABASE crowdsec_test TO crowdsec_test;"
}
dump() {
backup_file="${1?Missing file to backup database to}"
"${PGDUMP}" > "$backup_file" 2>/dev/null
}
restore() {
backup_file="${1?missing file to restore database from}"
[ -f "$backup_file" ] || die "Backup file $backup_file doesn't exist"
"${PGRESTORE}" < "$backup_file" #seems that in some system it needs for two run
}
config_yaml() {
yq '
.db_config.type=strenv(DB_BACKEND)|
.db_config.user="crowdsec_test" |
.db_config.password="crowdsec_test" |
.db_config.db_name="crowdsec_test" |
.db_config.host=strenv(PGHOST) |
.db_config.port=env(PGPORT) |
.db_config.sslmode="disable" |
del(.db_config.db_path)
' -i "${CONFIG_YAML}"
}
[ $# -lt 1 ] && about
case "$1" in
setup)
setup
;;
config-yaml)
config_yaml
;;
dump)
shift
dump "$@"
;;
restore)
shift
restore "$@"
;;
exec_sql)
shift
exec_sql "$@"
;;
*)
about
;;
esac;