Dnf update | rpm -qa | database disk image is malformed | error: SELECT hnum, blob FROM 'Packages': 11: database disk image is malformed

I ran a dnf update and got the error error: SELECT hnum, blob FROM 'Packages': 11: database disk image is malformed. I'm on Fedora 35, but found this issue affecting several others on older versions as well.

I thought this was a dnf error, but it seems like it's actually an issue with rpm. I have no idea what caused it, and I don't know why this fixed it. Use with caution.

What actually worked

I moved the rpm database files from /var/lib/rpm to /var/lib/rpm.bak, then used rpm --rebuilddb, then re-instaded the original rpm databases, and dnf update worked.

All these commands will require sudo. If you're lazy, you can sudo bash, but then be SURE to exit after you're done to leave the dangerous sudo bash environment.

Commands: (use at your own risk)

cd /var/lib # rpm files are at /var/lib/rpm/*
mv rpm rpm.bak # keep old tables safe
mkdir rpm # remake the dir
touch rpm/.rpm.lock # create the lock file for rpm transaction
rpm --rebuilddb # make new tables (and probably do other stuff?)
mv rpm rpm.bak2 # move the "new" tables
mv rpm.bak rpm # restore the old tables 

Then, sudo dnf update worked!

Things that didn't fix it (but maybe helped fix it?)

dnf clean all & makecache might have been crucial, and you might need to run them. I don't know.

dnf clean all
dnf makecache
# This may be from an old version of rpm?
rpm --builddb

Errors in the process

I had an error with rpm --rebuilddb because the transaction lock was not present, so i justed touched the file to created it

error: can't create transaction lock on /var/lib/rpm/.rpm.lock (No such file or directory)

Before mv rpm rpm.bak, rpm --rebuilddb gave me the same error as rpm -qa and dnf update:

SELECT hnum, blob FROM 'Packages': 11: database disk image is malformed" error

Recommended Reading