This commit is contained in:
2026-03-05 01:34:55 +01:00
parent 57d0f57924
commit c7d06858b6
2 changed files with 34 additions and 4 deletions

View File

@@ -10,7 +10,13 @@ replace_in_sqlite_db() {
exit 1
fi
echo "Starting safe replacement of '$OLD_STRING' with '$NEW_STRING' in '$DB_PATH'..."
# Check if jq is installed
if ! command -v jq &> /dev/null; then
echo "Error: 'jq' is not installed. Please install it first (e.g., 'sudo apt install jq')."
exit 1
fi
echo "Starting JSON-aware replacement of '$OLD_STRING' with '$NEW_STRING' in '$DB_PATH'..."
# Create a backup of the original database
local BACKUP_PATH="${DB_PATH}.bak"
@@ -20,18 +26,42 @@ replace_in_sqlite_db() {
local DUMP_PATH="${DB_PATH}.sql"
sqlite3 "$DB_PATH" ".dump" > "$DUMP_PATH"
# Replace strings in the SQL dump
sed -i "s|$OLD_STRING|$NEW_STRING|g" "$DUMP_PATH"
# Create a temporary file for the modified SQL dump
local MODIFIED_DUMP_PATH="${DB_PATH}.modified.sql"
# Process the SQL dump line by line
while IFS= read -r line; do
# Check if the line contains JSON data (simplistic check for quotes and brackets)
if [[ "$line" =~ [\"{][^"\{]*["\}][^"\{]*$OLD_STRING[^"\{]*[\}"] ]]; then
# Use jq to replace strings in JSON fields
echo "$line" | jq --arg old_str "$OLD_STRING" --arg new_str "$NEW_STRING" '
walk(if type == "string" then gsub($old_str; $new_str) else . end)
' > /dev/null 2>&1
# If jq fails (not valid JSON), fall back to sed
if [ $? -ne 0 ]; then
echo "$line" | sed "s|$OLD_STRING|$NEW_STRING|g"
else
echo "$line" | jq --arg old_str "$OLD_STRING" --arg new_str "$NEW_STRING" '
walk(if type == "string" then gsub($old_str; $new_str) else . end)
'
fi
else
# Use sed for non-JSON fields
echo "$line" | sed "s|$OLD_STRING|$NEW_STRING|g"
fi
done < "$DUMP_PATH" > "$MODIFIED_DUMP_PATH"
# Create a new database from the modified SQL dump
local NEW_DB_PATH="${DB_PATH}.new"
sqlite3 "$NEW_DB_PATH" < "$DUMP_PATH"
sqlite3 "$NEW_DB_PATH" < "$MODIFIED_DUMP_PATH"
# Replace the original database with the new one
mv "$NEW_DB_PATH" "$DB_PATH"
# Clean up temporary files
rm "$DUMP_PATH"
rm "$MODIFIED_DUMP_PATH"
echo "Replacement completed in '$DB_PATH'. Original database backed up to '$BACKUP_PATH'."
}

Binary file not shown.