Files
CloudDeploy/prepdb.sh
2026-03-05 01:39:42 +01:00

85 lines
3.0 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."
exit 1
fi
echo "Starting replacement of '$OLD_STRING' with '$NEW_STRING' in '$DB_PATH'..."
# Create a backup of the original database
local BACKUP_PATH="${DB_PATH}.bak"
cp "$DB_PATH" "$BACKUP_PATH"
# Begin a transaction
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 columns in the table
sqlite3 "$DB_PATH" "PRAGMA table_info($TABLE);" | awk -F'|' '{print $2","$3}' | while IFS=, read -r COLUMN COLUMN_TYPE; do
# Skip empty lines
if [ -z "$COLUMN" ]; then
continue
fi
echo " Processing column: $COLUMN (type: $COLUMN_TYPE)"
# Skip BLOB columns to avoid corruption
if [[ "$COLUMN_TYPE" == "BLOB" ]]; then
echo " Skipping BLOB column: $COLUMN"
continue
fi
# Check if the column might contain JSON data
local IS_JSON=$(sqlite3 "$DB_PATH" "SELECT COUNT(*) FROM $TABLE WHERE json_valid($COLUMN) = 1 LIMIT 1;")
if [ "$IS_JSON" -gt 0 ]; then
echo " Detected JSON data in column $COLUMN. Using json_replace()."
# Use json_replace for JSON columns
sqlite3 "$DB_PATH" "
UPDATE $TABLE
SET $COLUMN = json_replace($COLUMN, '$OLD_STRING', '$NEW_STRING')
WHERE json_valid($COLUMN) = 1 AND json_type($COLUMN) IS NOT NULL;
"
else
echo " Column $COLUMN is not JSON. Using replace()."
# Use replace for non-JSON columns
sqlite3 "$DB_PATH" "
UPDATE $TABLE
SET $COLUMN = replace($COLUMN, '$OLD_STRING', '$NEW_STRING')
WHERE $COLUMN LIKE '%$OLD_STRING%';
"
fi
done
done
# Commit the transaction
sqlite3 "$DB_PATH" "COMMIT;"
echo "Replacement completed in '$DB_PATH'. Original database backed up to '$BACKUP_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?"