66 lines
2.3 KiB
Bash
66 lines
2.3 KiB
Bash
# sqlite db replace function
|
|
replace_in_sqlite_db() {
|
|
local DB_PATH="$1"
|
|
local OLD_STRING="$2"
|
|
local NEW_STRING="$3"
|
|
|
|
# Check if the database file exists
|
|
if [ ! -f "$DB_PATH" ]; then
|
|
echo "Error: Database file '$DB_PATH' does not exist."
|
|
return 1
|
|
fi
|
|
|
|
echo "Starting safe replacement of '$OLD_STRING' with '$NEW_STRING' in '$DB_PATH'..."
|
|
|
|
# Escape single quotes for SQL
|
|
local OLD_STRING_ESC=$(printf "%s" "$OLD_STRING" | sed "s/'/''/g")
|
|
local NEW_STRING_ESC=$(printf "%s" "$NEW_STRING" | sed "s/'/''/g")
|
|
|
|
# Begin a transaction for safety
|
|
sqlite3 "$DB_PATH" "BEGIN TRANSACTION;"
|
|
|
|
# Get a list of all tables in the database
|
|
local TABLES
|
|
TABLES=$(sqlite3 "$DB_PATH" ".tables")
|
|
|
|
# Loop through each table
|
|
for TABLE in $TABLES; do
|
|
echo "Processing table: $TABLE"
|
|
|
|
# Get a list of all non-BLOB columns in the table
|
|
sqlite3 "$DB_PATH" "PRAGMA table_info($TABLE);" | awk -F'|' '
|
|
{
|
|
if ($3 != "BLOB") {
|
|
print $2
|
|
}
|
|
}' | while read -r COLUMN; do
|
|
# Skip empty lines
|
|
if [ -n "$COLUMN" ]; then
|
|
echo " Processing column: $COLUMN"
|
|
|
|
# Update only rows where the column contains OLD_STRING
|
|
sqlite3 "$DB_PATH" "
|
|
UPDATE $TABLE
|
|
SET $COLUMN = replace(CAST($COLUMN AS TEXT), '$OLD_STRING_ESC', '$NEW_STRING_ESC')
|
|
WHERE CAST($COLUMN AS TEXT) LIKE '%$OLD_STRING_ESC%';
|
|
"
|
|
fi
|
|
done
|
|
done
|
|
|
|
# Commit the transaction
|
|
sqlite3 "$DB_PATH" "COMMIT;"
|
|
|
|
echo "Safe replacement completed in '$DB_PATH'."
|
|
}
|
|
|
|
#set script directory
|
|
scriptdir="$(dirname "$(realpath "$0")")"
|
|
|
|
#example usage: replace_in_sqlite_db "database.sqlite" "Europe/Amsterdam" "UTC"
|
|
cp $scriptdir/stacks/npm/data/database-pre.sqlite $scriptdir/stacks/npm/data/database.sqlite
|
|
replace_in_sqlite_db "$scriptdir/stacks/npm/data/database.sqlite" "sdgserver.online" "?domain?"
|
|
replace_in_sqlite_db "$scriptdir/stacks/npm/data/database.sqlite" "192.168.2.132" "?localip?"
|
|
replace_in_sqlite_db "$scriptdir/stacks/npm/data/database.sqlite" "z5fGWz2i0q" "?adminpass?"
|
|
replace_in_sqlite_db "$scriptdir/stacks/npm/data/database.sqlite" "0.0.0.0/0" "?localip?"
|