diff --git a/prepdb.sh b/prepdb.sh index f91b8f7..20390f3 100644 --- a/prepdb.sh +++ b/prepdb.sh @@ -20,11 +20,11 @@ replace_in_sqlite_db() { local OLD_STRING_ESC=$(printf '%s\n' "$OLD_STRING" | sed "s/'/''/g") local NEW_STRING_ESC=$(printf '%s\n' "$NEW_STRING" | sed "s/'/''/g") - # Begin a transaction - sqlite3 "$DB_PATH" "BEGIN TRANSACTION;" || { + # Start a transaction with immediate mode for better locking + if ! sqlite3 "$DB_PATH" "BEGIN IMMEDIATE TRANSACTION;"; then echo "Error: Failed to begin transaction" exit 1 - } + fi # Get a list of all tables in the database local TABLES @@ -34,6 +34,9 @@ replace_in_sqlite_db() { exit 1 } + # Track if we made any changes + local CHANGES_MADE=false + # Loop through each table for TABLE in $TABLES; do echo "Processing table: $TABLE" @@ -65,21 +68,38 @@ replace_in_sqlite_db() { fi # Update only rows where the column contains OLD_STRING - if ! sqlite3 "$DB_PATH" " + if sqlite3 "$DB_PATH" " UPDATE $ESCAPED_TABLE SET $ESCAPED_COLUMN = replace(CAST($ESCAPED_COLUMN AS TEXT), '$OLD_STRING_ESC', '$NEW_STRING_ESC') WHERE CAST($ESCAPED_COLUMN AS TEXT) LIKE '%$OLD_STRING_ESC%'; " 2>/dev/null; then + CHANGES_MADE=true + else echo " Warning: Failed to update table $TABLE, column $COLUMN" fi fi done done - # Commit the transaction - if ! sqlite3 "$DB_PATH" "COMMIT;" 2>/dev/null; then - echo "Warning: Failed to commit transaction. Some changes may not have been applied." + # Try to commit the transaction with retries + local RETRIES=3 + local COMMIT_SUCCESS=false + + while [ $RETRIES -gt 0 ]; do + if sqlite3 "$DB_PATH" "COMMIT;" 2>/dev/null; then + COMMIT_SUCCESS=true + break + else + echo "Warning: Failed to commit transaction, retrying ($RETRIES attempts left)..." + sleep 1 + ((RETRIES--)) + fi + done + + if [ "$COMMIT_SUCCESS" = false ]; then + echo "Error: Failed to commit transaction after multiple attempts" sqlite3 "$DB_PATH" "ROLLBACK;" 2>/dev/null + exit 1 else echo "Replacement completed in '$DB_PATH'. Original database backed up to '$BACKUP_PATH'." fi