This commit is contained in:
2026-03-05 01:28:04 +01:00
parent bc079a7874
commit 57d0f57924
2 changed files with 18 additions and 26 deletions

View File

@@ -45,41 +45,33 @@ replace_in_sqlite_db() {
# Check if the database file exists # Check if the database file exists
if [ ! -f "$DB_PATH" ]; then if [ ! -f "$DB_PATH" ]; then
echo "Error: Database file '$DB_PATH' does not exist." echo "Error: Database file '$DB_PATH' does not exist."
return 1 exit 1
fi fi
echo "Starting brute-force replacement of '$OLD_STRING' with '$NEW_STRING' in '$DB_PATH'..." echo "Starting safe replacement of '$OLD_STRING' with '$NEW_STRING' in '$DB_PATH'..."
# Escape single quotes for SQL # Create a backup of the original database
local OLD_STRING_ESC=$(echo "$OLD_STRING" | sed "s/'/''/g") local BACKUP_PATH="${DB_PATH}.bak"
local NEW_STRING_ESC=$(echo "$NEW_STRING" | sed "s/'/''/g") cp "$DB_PATH" "$BACKUP_PATH"
# Get a list of all tables in the database # Dump the database to SQL
local TABLES local DUMP_PATH="${DB_PATH}.sql"
TABLES=$(sqlite3 "$DB_PATH" ".tables") sqlite3 "$DB_PATH" ".dump" > "$DUMP_PATH"
# Loop through each table # Replace strings in the SQL dump
for TABLE in $TABLES; do sed -i "s|$OLD_STRING|$NEW_STRING|g" "$DUMP_PATH"
echo "Processing table: $TABLE"
# Get a list of all columns in the table # Create a new database from the modified SQL dump
local COLUMNS local NEW_DB_PATH="${DB_PATH}.new"
COLUMNS=$(sqlite3 "$DB_PATH" "PRAGMA table_info($TABLE);" | awk -F'|' '{print $2}' | grep -v '^$') sqlite3 "$NEW_DB_PATH" < "$DUMP_PATH"
# Loop through each column # Replace the original database with the new one
for COLUMN in $COLUMNS; do mv "$NEW_DB_PATH" "$DB_PATH"
echo " Processing column: $COLUMN"
# Update every cell in the column, casting to TEXT to force string replacement # Clean up temporary files
sqlite3 "$DB_PATH" " rm "$DUMP_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%';
"
done
done
echo "replacement of '$OLD_STRING' with '$NEW_STRING' completed in '$DB_PATH'." echo "Replacement completed in '$DB_PATH'. Original database backed up to '$BACKUP_PATH'."
} }
#example usage: replace_in_sqlite_db "database.sqlite" "Europe/Amsterdam" "UTC" #example usage: replace_in_sqlite_db "database.sqlite" "Europe/Amsterdam" "UTC"

Binary file not shown.