DISABLE FDs (REMOVE ME).
[jackhill/mal.git] / plpgsql / wrap.sh
CommitLineData
adc5b4fb
JM
1#!/bin/bash
2
adc5b4fb 3RL_HISTORY_FILE=${HOME}/.mal-history
5340418b 4SKIP_INIT="${SKIP_INIT:-}"
08e44c41
JM
5PSQL_USER="${PSQL_USER:-postgres}"
6
7PSQL="psql -q -t -A -v ON_ERROR_STOP=1 ${PSQL_USER:+-U ${PSQL_USER}}"
5340418b
JM
8[ "${DEBUG}" ] || PSQL="${PSQL} -v VERBOSITY=terse"
9
df4c2c1a
JM
10# If mal DB is not there, force create of it
11dbcheck=$(${PSQL} -c "select 1 from pg_database where datname='mal'")
12[ -z "${dbcheck}" ] && SKIP_INIT=
13
494792ab
JM
14STDOUT_PID= STDIN_PID=
15cleanup () {
16 trap - TERM QUIT INT EXIT
17 # Make sure input stream is closed. Input subprocess will do this
18 # for normal terminal input but in the runtest.py case it does not
19 # get a chance.
20 ${PSQL} -dmal -c "SELECT io.close(0);" > /dev/null
21 [ "${STDIN_PID}" ] && kill ${STDIN_PID} 2>/dev/null
22}
23
adc5b4fb 24# Load the SQL code
494792ab
JM
25trap "cleanup" TERM QUIT INT EXIT
26${PSQL} -tc "SELECT 1 FROM pg_database WHERE datname = 'mal'" \
27 | grep -q 1 || ${PSQL} -c "CREATE DATABASE mal"
28#[ "${SKIP_INIT}" ] || ${PSQL} -dmal -f $1 > /dev/null
29[ "${SKIP_INIT}" ] || ${PSQL} -dmal -f $1
5340418b 30
494792ab 31${PSQL} -dmal -c "SELECT io.open(0); SELECT io.open(1);" > /dev/null
767d735d 32
97c0256d 33# Stream from table to stdout
8e266c18
JM
34(
35while true; do
494792ab 36 out="$(${PSQL} -dmal -c "SELECT io.read_or_error(1)" 2>/dev/null)" || break
767d735d 37 echo "${out}"
8e266c18
JM
38done
39) &
494792ab 40STDOUT_PID=$!
5340418b 41
53105a77 42# Perform readline input into stream table when requested
8e266c18 43(
97c0256d 44[ -r ${RL_HISTORY_FILE} ] && history -r ${RL_HISTORY_FILE}
53105a77 45while true; do
494792ab
JM
46 prompt=$(${PSQL} -dmal \
47 -c "SELECT io.wait_rl_prompt(0);" 2>/dev/null) || break
48 IFS= read -u 0 -r -e -p "${prompt}" line || break
53105a77
JM
49 if [ "${line}" ]; then
50 history -s -- "${line}" # add to history
51 history -a ${RL_HISTORY_FILE} # save history to file
52 fi
5340418b 53
53105a77 54 ${PSQL} -dmal -v arg="${line}" \
494792ab 55 -f <(echo "SELECT io.writeline(:'arg', 0);") >/dev/null || break
adc5b4fb 56done
494792ab 57${PSQL} -dmal -c "SELECT io.close(0);" > /dev/null
8e266c18 58) <&0 >&1 &
494792ab 59STDIN_PID=$!
8e266c18 60
df4c2c1a 61res=0
8e266c18
JM
62shift
63if [ $# -gt 0 ]; then
64 # If there are command line arguments then run a command and exit
65 args=$(for a in "$@"; do echo -n "\"$a\" "; done)
66 ${PSQL} -dmal -v args="(${args})" \
494792ab 67 -f <(echo "SELECT mal.MAIN('$(pwd)', :'args');") > /dev/null
df4c2c1a 68 res=$?
8e266c18
JM
69else
70 # Start main loop in the background
494792ab 71 ${PSQL} -dmal -c "SELECT mal.MAIN('$(pwd)');" > /dev/null
df4c2c1a 72 res=$?
8e266c18 73fi
494792ab 74wait ${STDOUT_PID}
df4c2c1a 75exit ${res}