2026-03-13 05:15:02 +01:00

90 lines
2.2 KiB
Bash

#!/bin/bash
# Copyright © 2012-2026 ScriptFanix
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# A copy of the GNU General Public License v3 is includded in the LICENSE file
# at the root of the project.
Update() {
#Update table set_key set_value [set_key set_value […]] < where_key where_operator where_value
# [where_key where_operator where_value
# […]]
local \
table="$1" \
key \
argument \
operator \
value \
set_statement \
where_keys \
where_values \
what \
where_statement \
results
shift
# Parse positional args as alternating key/value for the SET clause
what=key
for argument
do
case $what in
key)
# Backtick-quote column name to handle reserved
# words
set_statement="${set_statement:+${set_statement},}\`$argument\`"
what=value
;;
value)
case $argument in
'::AtOM:FT::'*)
# Force-text: strip prefix and
# quote as string
argument="${argument//::AtOM:FT::/}"
set_statement+=" = "'"'"${argument//\"/\"\"}"'"'
;;
'NULL')
set_statement+=" = NULL"
;;
+([0-9])?(.+([0-9])))
# Numeric value: store unquoted
set_statement+=" = $argument"
;;
*)
set_statement+=" = "'"'"${argument//\"/\"\"}"'"'
;;
esac
what=key
;;
esac
done
# Build WHERE clause from stdin
while read key operator value
do
(( ${#where_statement} )) && where_statement+=( "AND" )
case $value in
'NULL')
where_statement+=( "$key is NULL" )
;;
+([0-9.]))
# Numeric: compare without quotes
where_statement+=( "$key $operator $value" )
;;
*)
where_statement+=( "$key $operator "'"'"${value//\"/\"\"}"'"' )
;;
esac
done
echo "UPDATE '$table' SET" \
"$set_statement" \
"WHERE" \
"${where_statement[@]}" \
";" >&3
}