Thankyou
@ChuckPa You might want to mention in the Instructions that on macOS ARM64 you need to either disable Gatekeeper or remove the com.apple.quarantine attribute through the Terminal.
MacOS Users:
How’s this read for inclusion in the documentation ?
macOS users: “can’t be opened” after downloading DBRepair? Here’s the fix.
DBRepair will refuse to run on MacOS, even after chmod +x.
This isn’t a bug — it’s macOS Gatekeeper.
Files downloaded from the internet are automatically quarantined, and macOS won’t execute a quarantined, unsigned binary until you clear that flag.
Two ways to fix it, whichever you prefer:
- Terminal:
xattr -d com.apple.quarantine DBRepair
- Finder: right-click
DBRepair, choose Open, then confirm in the dialog.
This only needs to be done once, right after downloading. For background, here’s Apple’s own documentation: https://support.apple.com/en-us/102445
Note that specifically ARM64 binaries cannot be whitelisted through the Privacy and Security settings, only Universal Apps and x86_64 apps can be whitelisted with the Open trick. If you download an unsigned ARM64 binary you have to use Terminal or you’ll get a misleading “App is damaged and could not be opened” error.
There are other Arm64 (M2 & M4) users here who manage DBRepair ok.
DBREPAIR IS A TERMINAL SESSION PROGRAM
it’s not a GUI APP
I’ll be happy to write a GUI app and charge for it if that’s what the community wants.
I think you’re misinterpreting what I’m saying. All I’m saying is that GateKeeper on macOS doesn’t let you trust an unsigned ARM64 app through the Privacy and Security settings like it would with an Intel or Universal app. It will always report the app as damaged because it is unsigned. The only way to keep GateKeeper enabled and execute an unsigned ARM64 binary is to trust it in the Terminal with xattr.
You don’t have to run any terminal commands. I have an M2 macstudio. I ran the dbrepair and it gave me the error. I opened up settings went down to privacy & security then told it to open the program. It asked for my password or fingerprint and once I entered that it opened no problem. Any time you open an unsigned app it will error out. Just go to privacy & security say allow the app to open and input your password then it will open. No need for terminal
Everyone.
I saw your replies. THANK YOU!
I just got a message that I’m using the wrong tool. (story of my life.. haha)
I will rework my ideas and share again
ALL:
We’ve arrived.
Welcome to DBRepair beta ! 
I’ve done a lot of cleanup in preparation for production status.
If it’s going to break, now is the time 
Beta test expiration is set at 21 days.
Release Notes
v00.99.11
* Version Format - Changed version format to new publication format.
* B-Tree Errors - DBRepair can now detect B-tree (hard damage) in the
database and deal with it automatically. Previously it
might fail after reconstructing a DB with this type
damage. Now it knows what to do.
* Expunge - Expunge has been expanded.
- Expunge age may be set to a value other than the
default 180 days. Limit 3000 days
- Expunge removes "0" accounts, NULL accounts, or
age-expired accounts.
- Expunge removes all statistics associated with those
accounts.
- When expunge is completed, it prints a report showing
Name or account ID and Last Active plus a total
number of accounts removed from the DB.
* Identification - DBRepair is now smarter at identifying PMS database
versions.
- If DBRepair can read your log files and that version is
known, it will have authoritative information to
complete all repairs (normal operation).
Without logs, but with a readable database set, it will
attempt to identify the PMS version it's from and load the
authoritative schemas for that version if in its list of
known versions (PMS 1.40.0 -> PMS 1.43.4 -- currently)
DBRepair can use your PMS-generated backups as a
reasonably authoritative source if it doesn't know the
exact version. Missing table, index, trigger, and
virtual table detection degrades at this point since it
has no authoritative source.
- Lastly, if no backups are available, DBRepair will use
your live DBs as the "Best Effort" source of information.
At this point, it can still repair SQLite DB damage and
rebuild anything it definitively identifies.
DBRepair will always, minimally, be able to perform basic
sqlite database checks, repairs and optimizations
* Command Options - DBRepair now supports two new options in addition to
reading the same info from Environment variables
--cacheage N eg: --cacheage 90 (sets cache age limit to 90 days for pruning old files)
--expungeage N eg: --expungeage 90 (sets age limit to 90 days )
( --cacheage is equivalent to DBREPAIR_CACHEAGE variable )
( --expungeage is equivalent to DBREPAIR_EXPUNGEAGE variable )
Known limitation:
* -n/--nocommit - Only run ONE command per invocation while -n is active.
-n prevents the repaired database from ever being made
"live", so a second command chained after it in the same
invocation (e.g. "auto expunge") does NOT see the first
command's result - it still operates on the original,
unrepaired database. Run commands one at a time under
-n.
* GitHub - Preparations are ready for going live on GitHub. DBRepair
will support a "Update" function again with Download capability (no installs)
For your consideration:
![]()
Peek at the readme. Comments Welcomed!
- The README will be getting a lot of attention over the next 3 weeks to get all the old ‘script-isms’ out of it and fully updated with all the new capabilities.
This is a working draft. It’s got new and (obviously) old content.
I’ll get it cleaned up these next few weeks.
Don’t be confused when you suddenly see a disconnect.
README
Windows Users:** Beginning with DBRepair 26.10.00, DBRepair is no longer a shell script. It’s a fully stand-alone executable program on Linux, macOS and Windows.
Previous versions of DBRepair required separate .bat or .ps1 scripts, which have now been completely deprecated. Just download, extract, and run.
DBRepair is a standalone utility run from a command line (terminal, Command
Prompt/PowerShell, or ssh/putty session) on the local host machine. It must have
sufficient privileges to read/write the databases. Because DBRepair is
distributed as a compiled executable, it requires no external runtime
dependencies.
If sufficient privileges exist (root/Administrator), and are supported by the environment, the options to start and stop PMS are presented as well.
Situations and errors commonly seen include:
1. Searching is sluggish or broken
2. Database is malformed / damaged / corrupted
3. Database has bloated from media addition or changes
4. Damaged indexes / Rows out of order
5. Tables, Indexes, or other items missing from databases (seen in logs)
6. Importing data from other databases (watch history)
7. Cleaning up operational temp files which PMS has forgotten
Functions provided
The utility accepts command names.
Command names may be upper/lower case and may also be abbreviated (4 character minimum).
The following commands (or their number), listed in alphabetical order, are accepted as input.
AUTO(matic) - Intelligently, stop PMS, check the databases, do what's needed, and restart PMS as needed.
CHEC(k) - Check the main and blob databases integrity (includes FTS index check)
DEFL(ate) - Deflate a bloated PMS database (faulty statistics data)
EXIT - Exit the utility
EXPU(nge) - Remove view history/statistics for non-existent, NULL, or age-expired accounts
HIST(ory) - Show the command history of this session
IGNOre/HONOr - Ignore/Honor constraint errors when IMPORTing additional data into DB.
IMPO(rt) - Import viewstate / watch history from another database
ORPH(ans) - Search for and report any orphaned media items
PRUN(e) - Remove old image files from PhotoTranscoder cache & all temp files left by PMS
QUIT - Quit immediately, keeping all temporary database files
REIN(dex) - Rebuild the database indexes (includes FTS indexes)
REPA(ir) - Extract and rebuild usable databases from the existing data
REPL(ace) - Replace the existing databases with a PMS-generated backup
REVE(rt) - Revert the databases to immediately before a selected history index
SHOW - Show the log file
STAR(t) - Start PMS (not available on all platforms)
STAT(us) - Report status of PMS (run-state and databases)
STOP - Stop PMS (not available on all platforms)
VACU(um) - Vacuum the databases
The menu
The menu gives you the option to enter either a ‘command number’ or the ‘command name/abbreviation’.
For clarity, each command’s name is ‘quoted’.
Database Repair Utility for Plex Media Server (_host_configuration_name_)
Version 26.10.00
Select
1 - 'stop' - Stop PMS.
2 - 'automatic' - Stop, Check, Repair/Optimize, and Resume as needed.
3 - 'check' - Perform integrity check of database and FTS indexes.
4 - 'vacuum' - Remove empty space from database without optimizing.
5 - 'repair' - Repair/Optimize databases.
6 - 'reindex' - Rebuild database indexes.
7 - 'start' - Start PMS
8 - 'import' - Import watch history from another database independent of Plex. (risky).
9 - 'replace' - Replace current databases with newest usable backup copy (interactive).
10 - 'show' - Show logfile.
11 - 'status' - Report status of PMS (run-state and databases).
12 - 'history' - Show command history of this session.
13 - 'revert' - Revert DBs to immediately before history index.
21 - 'prune' - Remove old image files from PhotoTranscoder cache & all temp files left by PMS.
22 - 'expunge' - Remove view history of non-existent Plex accounts
23 - 'deflate' - Deflate a bloated PMS main database.
31 - 'orphans' - Search for and report any orphaned media items.
42 - 'ignore' - Ignore duplicate/constraint errors.
98 - 'quit' - Quit immediately. Keep all temporary files.
99 - 'exit' - Exit with cleanup options.
Enter command # -or- command name (4 char min) :
Hosts currently supported
Because DBRepair is a standalone binary, it runs natively across a wide variety
of environments. The utility must be run locally on the host where the data
resides.
- Windows (Native executable)
- Apple (macOS)
- Linux (Workstation & Server - multiple distributions)
- FreeBSD (14+)
- NAS Appliances (ASUSTOR, Netgear OS5, QNAP QTS/QuTS, Synology DSM 6/7, Western Digital OS5)
- Docker containers via ‘docker exec’ (Plex, Linuxserver.io, BINHEX, HOTIO, Podman)
Installation
Available Packages
DBRepair is packaged as a .zip archive for easy downloading. Each archive
contains the standalone executable for the target platform, along with the
README.md, ReleaseNotes, and License.md files.
The following architectures are supported:
- Windows (64-bit):
DBRepair-windows-x86_64.zip - macOS (Apple Silicon):
DBRepair-darwin-arm64.zip - macOS (Intel):
DBRepair-darwin-x86_64.zip - Linux (Intel 64-bit):
DBRepair-linux-x86_64.zip - Linux (ARM 64-bit):
DBRepair-linux-arm64.zip - Linux (ARM 32-bit):
DBRepair-linux-arm32.zip
Downloading
It is highly recommended to download the packaged .zip archive for your system.
Navigate to the latest release:
DBRepair Latest Release
and download the appropriate .zip file for your platform from the
Assets section.
(Advanced users: Raw binaries are also available in the release assets if you
prefer to download only the executable without the bundled documentation).
Moving the downloaded utility
Where to extract and place the utility varies from host to host.
Please use this table as a reference for where to put the extracted files.
Some hosts will not be listed here by name (e.g. Unraid, Proxmox).
They will likely be supported by the container/VM PMS runs in.
Vendor | Shared folder name | Recommended directory
-------------------+---------------------+------------------------------------------
Windows | Downloads | C:\Users\YourName\Downloads
Apple | Downloads | ~/Downloads
Arch Linux | N/A | Anywhere
ASUSTOR | Plex | /volume1/Plex
Binhex | N/A | Container root (adjacent /config)
Docker (Plex,LSIO) | N/A | Container root (adjacent /config)
Hotio | N/A | Container root (adjacent /config)
FreeBSD (14+) | N/A | Anywhere
Kubernetes | N/A | Container root (adjacent /config)
Linux (wkstn/svr) | N/A | Anywhere
MacOS | N/A | Anywhere
Netgear (ReadyNAS) | "your_choice" | "/data/your_choice"
QNAP (QTS/QuTS) | Public | /share/Public
SNAP | N/A | Anywhere
Synology (DSM 6) | Plex | /volume1/Plex (change volume as required)
Synology (DSM 7) | PlexMediaServer | /volume1/PlexMediaServer (change volume as required)
Western Digital | Public | /mnt/HD/HD_a2/Public (Does not support 'MyCloudHome' series)
Plex, inc and LSIO docker images are included in "Docker" platform category independent of the actual host.
Additional hosts and docker images can easily be supported in almost all cases with appropriate path
information. Please contact me as needed.
Getting a usable command line session
1. Windows
Open a Command window (cmd.exe or PowerShell). Right-click and "Run as Administrator" if required.
2. Linux
Open a terminal session and elevate to the root (sudo) user.
3. Accessing a NAS
Open a terminal/command line window on your computer.
type: ssh admin-username@IP.addr.of.NAS
General installation and usage instructions
1. Open your browser to https://github.com/ChuckPa/DBRepair/releases/latest
2. Download the appropriate `.zip` archive for your OS and architecture.
3. Place the archive in the appropriate directory on the local host system.
4. Open a command line session (usually Command Prompt, Terminal, or SSH).
5. Elevate privilege level to Administrator or root (sudo) if needed.
6. Extract the `.zip` archive.
7. Change directory (`cd`) into the extraction directory.
8. Give the binary 'execute' permission if on macOS/Linux (`chmod +x dbrepair`).
9. Invoke `dbrepair.exe` (Windows) or `./dbrepair` (macOS/Linux).
EXAMPLE: To install & launch on Windows (PowerShell)
cd C:\Users\YourName\Downloads
Expand-Archive -Path DBRepair-windows-x86_64.zip -DestinationPath .\DBRepair
cd .\DBRepair
.\dbrepair.exe
EXAMPLE: To install & launch on Synology DSM 6 / DSM 7
cd /volume1/Plex # use /volume1/PlexMediaServer on DSM 7
sudo bash
unzip DBRepair-linux-x86_64.zip
chmod +x dbrepair
./dbrepair
EXAMPLE: Using DBRepair inside containers (manual start/stop included)
(Select containers allow stopping/starting PMS from the menu. See menu for details)
sudo docker exec -it plex /bin/bash
# Download, extract, and run
# Example assumes you have wget installed in the container
wget https://github.com/ChuckPa/DBRepair/releases/latest/download/DBRepair-linux-x86_64.zip
unzip DBRepair-linux-x86_64.zip
chmod +x dbrepair
./dbrepair
EXAMPLE: Using DBRepair on regular Linux native host (Workstation/Server)
sudo bash
cd /path/to/download/directory
unzip DBRepair-linux-x86_64.zip
chmod +x dbrepair
./dbrepair auto exit
EXAMPLE: Using DBRepair from the command line on MacOS (on the administrator account)
osascript -e 'quit app "Plex Media Server"'
cd ~/Downloads
unzip DBRepair-darwin-arm64.zip # Or -x86_64 depending on Mac processor
chmod +x dbrepair
./dbrepair
Typical usage
This utility can only operate on PMS when PMS is in the stopped state.
If PMS is running when you startup the utility, it will tell you.
A. The most common usage will be the “Automatic” function.
Automatic mode is where DBRepair determines which steps are needed to make your database run optimally.
For most users, Automatic is equivalent to 'Check, Repair (no reindex required)'.
This repairs minor damage, vacuums out all the unused records, and rebuilds search indexes in one step.
B. Database is malformed (Backups of com.plexapp.plugins.library.db and com.plexap.plugins.library.blobs.db available)
Note: You may attempt “Repair” sequence
1. (3) Check - Confirm either main or blobs database is damaged
2. (9) Replace - Use the most recent valid backup
-- OR --
2. (5) Repair - If Replace fails, use Repair (5)
- (Replace can fail if the database has been damaged for a long time.)
4. (99) Exit
C. Database is malformed - No Backups
1. (3) Check - Confirm either main or blobs database is damaged
2. (5) Repair - Salvage as much as possible from the databases and rebuild them into a usable database.
3. (99) Exit
D. Database sizes excessively large/bloated when compared to amount of media indexed (item count)
1. (2) Auto - Perform automated check, repair of the deflated database
2. (99) Exit
E. User interface has become ‘sluggish’ as more media was added
1. (3) Check - Confirm there is no database damage
2. (5) Repair - You are not really repairing. You are rebuilding the DB in perfect sorted order.
3. (99) Exit
F. Undo
Undo is a special case where you need the utility to backup ONE step.
This is rarely needed. The only time you might want/need to backup one step is if Replace leaves you worse off
than you were before. In this case, UNDO then Repair. Undo can only undo the single most-recent action.
(Note: In a future release, you will be able to ‘undo’ every action taken until the DBs are in their original state)
G. HTTP 500 errors when adding to collections / FTS index corruption
This occurs when standard integrity_check passes but FTS (Full-Text Search) indexes are corrupted.
Symptoms: Adding items to collections fails, updating metadata fails, “database disk image is malformed”
during UPDATE operations even though Check reports databases are OK.
1. (3) Check - Will show "FTS index damaged" message
2. (6) Reindex - Rebuild indexes including FTS
3. (99) Exit
Alternatively, use (2) Automatic which will detect and repair FTS issues automatically.
Special considerations:
1. As stated above, this utility requires PMS to be stopped in order to do what it does.
2. - This utility CAN sit at the menu prompt with PMS running.
- You did a few things and want to check BEFORE exiting the utility
- If you don't like how it worked out,
-- STOP PMS
-- UNDO the last action and do something else
-- OR do more things to the databases
3. When satisfied, Exit the utility.
- There is no harm in keeping the database temp files (except for space used)
- ALL database temps are named with date-time stamps in the name to avoid confusion.
4. The Logfile ('show' command) shows all actions performed WITH timestamp so you can locate
intermediate databases if desired for special / manual recovery cases.
Community feedback has resulted in:
"98" or "Quit" - Get out now without deleting the temp databases (Usually
used only during unexpected failures)
"99" or "Exit" - Preferred way to exit and cleanup temp databases
Notice:
If command line EOF is encountered before Exit/Quit command received,
DBRepair will quit and KEEP all temporary files.
Also please be aware the utility understands interactive versus scripted mode.
Command line options
To avoid confusion and making the menu complicated, a few command line options have been added.
To use DBRepair when the container / host cannot be identified, --databases allows you
to specify the pathname from whichever context (namespace) DBRepair will be running in.
--databases Specify the path to the directory which contains the PMS databases.
DBRepair contains its own statically-linked SQLite library, so no separate “Plex SQLite”
path is needed.
When operating with this option, DBRepair will indicate it’s in Manual configuration mode.
You may still use other command line commands (batch mode) or use it normally in interactive mode.
If DBRepair can perfectly identify the version of your databases, you will have full capabilities
If not, DBRepair will look for your PMS-generated databases and use them as additional identification.
Scripting (command line arguments, aka ‘batch’) support
Certain platforms don’t provide for easy command line access.
To support those products, this utility can be operated by adding command line arguments.
Another use of this feature is to automate Plex Database maintenance
( Stop Plex, Run a sequence, Start Plex ) at a time when the server isn’t busy.
If you want simple automatic maintenance, “auto exit” is all that’s needed.
The command line arguments are the same as if typing at the menu.
Example: ./dbrepair auto exit (or .\dbrepair.exe auto exit on Windows)
This executes: Stop PMS, Automatic (intelligent check/repair), Start PMS, and Exit commands
Exiting
If no command modified the databases during the session, exit closes immediately with nothing to clean up.
If a command did modify the databases, you will be asked whether to keep the interim temp files created during this session.
If you’ve encountered any difficulties or aren’t sure what to do, don’t delete them.
You’ll be able to ask in the Plex forums about what to do. Be prepared to present the log file to them.
Sample interactive session
This is a typical manual session if you aren’t sure what to do and want the tool to decide.
$ ./dbrepair
Database Repair Utility for Plex Media Server (_host_configuration_name_)
Version 26.10.00
Select
1 - 'stop' - Stop PMS.
2 - 'automatic' - Stop, Check, Repair/Optimize, and Resume as needed.
3 - 'check' - Perform integrity check of database and FTS indexes.
4 - 'vacuum' - Remove empty space from database without optimizing.
5 - 'repair' - Repair/Optimize databases.
6 - 'reindex' - Rebuild database indexes.
7 - 'start' - Start PMS
8 - 'import' - Import watch history from another database independent of Plex. (risky).
9 - 'replace' - Replace current databases with newest usable backup copy (interactive).
10 - 'show' - Show logfile.
11 - 'status' - Report status of PMS (run-state and databases).
12 - 'history' - Show command history of this session.
13 - 'revert' - Revert DBs to immediately before history index.
21 - 'prune' - Remove old image files from PhotoTranscoder cache & all temp files left by PMS.
22 - 'expunge' - Remove view history of non-existent Plex accounts
23 - 'deflate' - Deflate a bloated PMS main database.
31 - 'orphans' - Search for and report any orphaned media items.
42 - 'ignore' - Ignore duplicate/constraint errors.
98 - 'quit' - Quit immediately. Keep all temporary files.
99 - 'exit' - Exit with cleanup options.
Enter command # -or- command name (4 char min) : auto
Stopping PMS. (60 second max delay)
Stopped PMS.
Checking the PMS databases...
Main DB is OK.
Blobs DB is OK.
Main and Blobs databases are healthy - nothing to do.
Starting PMS.
Started PMS.
...[Menu Redisplayed]...
Enter command # -or- command name (4 char min) : exit
$
Note: exit only prompts about keeping/discarding temporary work files when
a command actually modified the databases during the session. In the example
above, nothing needed repair, so it exits immediately with no prompt.
Logfile
The logfile (DBRepair.log) keeps track of all commands issues and their status (PASS/FAIL) with timestamp.
This can be useful when recovering from an interrupted session because temporary files are timestamped.
2023-02-25 16.14.39 - ============================================================
2023-02-25 16.14.39 - Session start: Host is Synology (DSM 7)
2023-02-25 16.14.56 - StopPMS - PASS
2023-02-25 16.16.06 - Check - Check com.plexapp.plugins.library.db - PASS
...
2023-02-25 16.38.58 - Session end.
Command Reference:
Automatic
Automatic provides fully automated processing in one step: it stops PMS if running, checks the
databases, repairs/optimizes only if damage is found (reindexing is included as part of Repair),
and resumes PMS afterward.
If the databases are already healthy, Automatic does nothing further and exits quickly.
In its current state, it will not automatically replace a damaged database from a backup (future)
Check
Checks the integrity of the Plex main and blobs databases.
Also performs FTS (Full-Text Search) index integrity checks. FTS indexes can become
corrupted even when standard integrity checks pass, causing operations like adding
items to collections to fail with “database disk image is malformed” errors.
If FTS corruption is detected, use ‘reindex’ (option 6) or ‘automatic’ (option 2)
to rebuild the FTS indexes.
Deflate
Repairs a known error in the PMS main database “statistics_bandwidth” table.
After repairing it, it purges all the errant data from the table (reducing DB size)
This task can take a significant amount of time. It’s frequently used when
the DB size is an order of magnitude above what it should be (e.g. 31 GB vs
206 MB). Reductions from 134 GB to 210 MB have been realized.
Deflating is an integral part of Auto & Repair functions.
(Auto will deflate the databases for you if needed).
Exit
Exits the utility and removes all temporary database files created during processing.
To save all intermediate databases, use the ‘Quit’ command.
Expunge
Removes view history and statistics left behind by accounts that no longer exist in Plex (account
ID “0”, NULL accounts, or accounts inactive beyond an age threshold).
The age threshold defaults to 180 days and can be changed with --expungeage N (or the
DBREPAIR_EXPUNGEAGE environment variable), up to a maximum of 3000 days.
When complete, Expunge prints a report listing each removed account (name or account ID) and its
last-active date, plus the total number of accounts removed.
Ignore / Honor
Toggle the state (ON/OFF) of the IGNORE flag. When ON, Duplicates and UNIQUE constraint errors will be ignored.
Caution is advised as other errors will be ignored during initial processing.
In ALL cases, DBRepair will never allow a bad database to be created.
Import
Imports (raw) watch history from another PMS database without ability to check validity
( This can have side effects of “negative watch count” being displayed. Caution is advised. )
Orphans
Searches for and reports media items (tracks, albums, episodes, etc.) that are orphaned in the
database - present but not connected to their parent item. Playback is unaffected, but a normal
‘Scan Files’ won’t fix this.
Orphans reports the specific library and item(s) affected so you can decide whether to use Plex’s
‘Plex Dance’ procedure or reload the missing media files to resolve it.
Prune
Checks the PhotoTransoder cache directory for JPG, JPEG, and PNG files older than 30 days and removes them.
Under normal operation, PMS manages this automatically.
Under certain conditions, PMS will fail to prune them (which is run during Scheduled Maintenance)
This command allows you to manually remove what PMS would do normally during that Scheduled Maintenance.
Prune will give you a report of the number of files removed upon completion.
Info: Initial pruning might take longer than expected.
Execution time, using a Synology DS418 as benchmark, is approximately 100,000 image files per 2 minutes.
Reindex
Reindex does a quick “Reindex” of the existing databases.
It’s not needed under normal “auto” or “repair” actions.
These indexes are used by PMS for searching (both internally and your typed searches)
Repair
If not already checked, performs an in-depth check and then repairs as needed.
Extracts/recovers all the usable data from the existing databases into text (SQL ascii) form.
Repair then creates new SQLite-valid databases from the extracted/recovered data.
The side effect of this process is a fully defragmented database (optimal for Plex use).
100% validity/usability by Plex is not guaranteed as the tool cannot validate each individual
record contained in the database. It can only validate at the SQLite level.
In most cases, Repair is the preferred option as the records extracted are only those SQLite deemed valid.
Replace
Looks through the list of available PMS backups.
Starting with the most recent PMS backup,
1. Check the both db files
2. If valid, offer as a replacement choice
3. If accepted (Y/N question) then use as the replacement
else advance to the next available backup
4. Upon completion, validate one final time.
Quit
Exits the utility but leaves the temporary databases intact (useful for making exhaustive backups)
Show
Shows the activity log. The activity log is date/time stamped of all activity.
Start
On platform environments which support it, and when invoked by the ‘root’ user, the tool can start PMS.
If not the ‘root’ user or on a platform which doesn’t support it, “Not available” will be indicated.
Stop
On platform environments which support it, and when invoked by the ‘root’ user, the tool can stop PMS.
If not the ‘root’ user or on a platform which doesn’t support it, “Not available” will be indicated.
PMS must be in the stopped state in order to operate on the database files.
Stopping / Starting in Containers (Special Considerations)
Stopping/starting PMS in containers depends on the container execution control mechanism
Some images are designed with an “Always Running” philosophy and do not allow the tool to stop/
start PMS while under program control.
In these image types, the only mechanism, subject to time constraints of any health check,
is to type: kill -15 $(pidof ‘Plex Media Server’)
at the container command line prior to invoking dbrepair and waiting for PMS to shutdown.
After DB tasks are completed, and you’ve exited the container, restart it normally through
your normal ‘docker start’ mechanism.
If your container (Image) supports start/stop , it will be shown in the menu for you to use.
If not, you’ll need to disable health checks before safely running this tool.
History
Shows the command history for this session (what was run, when, and its status), so you can decide
what point to ‘Revert’ back to if needed.
Revert
Reverts the databases to their state immediately before a selected point in this session’s
History. Choose the point from the ‘History’ listing.
Status
Reports the current status of PMS (running/stopped) and the databases for this session.
Vacuum
Instructs SQLite to remove the empty/deleted records and gaps from the databases.
This is most beneficial after deleting whole library sections.
For most users, the “automatic” command is the best method. It will regenerate the SQLite indexes
as part of the process.
Sqlite (hidden developer/debugging command)
.sqlite (must be typed in full - it is not part of the numbered menu and does not appear
in SHOW) launches a small, self-contained interactive SQLite shell (REPL) built directly
into DBRepair, using the exact same statically-linked SQLite/ICU build the rest of the tool
uses. It always starts connected to a scratch in-memory database - use .open to connect
to a real file.
Useful for inspecting database state directly - checking FTS index health, row counts,
schema, or running ad-hoc SQL - without needing a separate SQLite binary that understands
Plex’s ICU collation/tokenizer.
Dot-commands available inside the shell:
.bail on|off - Stop (nonzero exit) on the first statement error. Off by default.
.close - Close the active connection; reports whether the handle
actually cleared.
.dbinfo - Show page size, page count, encoding, and auto_vacuum mode.
.echo on|off - Print each statement's SQL text before its output. Off by default.
.exit / .quit - Leave the shell.
.ftsinfo <table> - Show row counts for an FTS4 table's shadow tables
(_content/_segments/_segdir/_docsize/_stat).
.indexes [pattern] - List indexes, optionally filtered by table name pattern.
.open [--readonly|--readwrite|--create] <file>
- Close the current connection and open <file>. --readwrite and
--create behave identically (read-write, create if missing) -
matching real sqlite3's own .open default. --readonly restricts
to read-only. Also accepts the short forms RO/RW/CREATE.
.schema [pattern] - Show CREATE statements, optionally filtered by name pattern.
.slots - List the 4-slot connection pool: which slot is active, its
path, and open/closed state.
.tables [pattern] - List tables/views, optionally filtered by name pattern.
Any other input is treated as SQL and executed against the active connection.
Example (checking FTS health from the command line without a separate SQLite build):
./dbrepair .sqlite
sqlite> .open --readonly /path/to/com.plexapp.plugins.library.db
sqlite> .ftsinfo fts4_metadata_titles_icu
Environment Variables
DBRepair now supports the use of environment variables to allow customization of some operations.
WARNING: Use of these variables may adverse impact PMS operation or performance. USE WITH CAUTION.
DBREPAIR_CACHEAGE - Specify the maximum age for PhotoTrancoder Cache images to be retained
Default DBREPAIR_CACHEAGE is set at 30 days.
You may override this by setting DBREPAIR_CACHEAGE=N, where N is the number of days worth of cache image
you wish to retain.
When using interactively, DBRepair will prompt you to confirm OK to remove and show you the cache age
Example: export DBREPAIR_CACHEAGE=20
Enter command # -or- command name (4 char min) : remove
Counting how many files are more than 20 days old.
OK to prune 4497 files? (Y/N) ?
DBREPAIR_PAGESIZE - Allows setting the Plex SQLite ‘page_size’.
Normal Linux (ext4, xfs) filesystems do not need this customization because the filesystem block size = 4096.
ZFS users sometimes need to customize their datasets to improve I/O performance (HDDs vs SSDs).
This capability allows them to compensate for some of those losses.
If present, sets the Plex SQLite ‘page_size’ for both Main and Blobs databases.
If not present, the default page size for the host OS is used (typically 4096 to match the OS page size).
When in use, you will see the message: “Setting Plex SQLite page size ($DbPageSize)”
This will be shown on the console output and reported in the logfile.
Constraints:
1. Must be a power of 2, with 1024 (2^10) as the Plex default. (per SQLite 3.12.0 documentation).
Any invalid value provided will be rounded up to the next integral value (1024, 2048, 4096 ... 65536)
This may or may not be the value you intended. Caution is advised.
2. May not exceed 65536 (per SQLite 3.12.0 documentation).
Any value exceeding 65536 will be truncated to 65536.
Validation
If the value of DBREPAIR_PAGESIZE is not compliant with requirements, a new value will be selected.
Typing errors will be rounded up (e.g 65535 vs 65536) to the next multiple of 1024 before validation
is performed.
If the value is invalid, an error will be printed and recorded in the logfile. The next higher power
of two will be selected.
If the value is too large, it will be reduced to the SQLite maximum of 65536.
Management
If you attempt to optimize your database but find the resultant performance is not to your liking,
you may try another value and run “automatic” again.
If you ultimately decide to run with the default values (4096),
- Remove the environment variable.
- Run DBRepair again using “automatic”. Your databases will revert to the host OS’s default.
Special considerations - MANUAL CONFIGURATION
Manual configuration is enabled by supplying the --databases command line argument.
It must precede all other options or commands on the command line.
–databases “/path/to/Databases”
DBRepair contains its own statically-linked SQLite library, so no separate “Plex SQLite”
path needs to be specified.
In manual configuration, DBRepair cannot identify which running PMS instance (if any) owns
the specified path, so it will not stop/start PMS itself. Stop PMS yourself first; DBRepair
will refuse to proceed and tell you to if it detects PMS running.
Scripted Example:
./dbrepair --databases “/real/host/directory/…/Databases” auto prune
Interactive Example:
./dbrepair --databases /real/host/directory/…/Databases
Special considerations - Synology DSM 7
Using DBRepair on Synology DSM 7 systems with Task Scheduler requires special handling.
DSM 7 has additional security (app-armor). Care must be taken to not violate this.
One exception must be implemented. Care must be used to implement.
DSM 7 - Step 1 - Designate a DSM username which will run DBRepair
- Creating a to-task username with a complex password is best practice
- Create a Scheduled task, user-script:
- Runs as root
- Emails you the result
- Is not scheduled
- Is disabled in the Task Scheduler task list
Contents of the user-script are:
#!/bin/bash
#
# This script grants the given syno username (your username)
# the ability to elevate to 'root' privilege for use with DBRepair
#
# Set your desired Syno username here (no spaces in the username)
MyUsername="chuck"
# Confirm username exists
if [ "$(id "$MyUsername")" = "" ]; then
echo ERROR: No such user \'$MyUsername\'
exit 1
fi
# Remove old record
sed -i s/^${MyUsername}.\*$// /etc/sudoers
# Add myself to sudoers
echo "$MyUsername" 'ALL=(ALL) NOPASSWD: ALL' >> /etc/sudoers
DSM 7 - Step 2 - Run DBRepair as the designated username
With the security now set, DBRepair can be invoked from Task Scheduler.
Download and place the extracted dbrepair binary in the desired location (PlexMediaServer shared folder ok)
Make certain it’s executable.
Create Scheduled Task - User-Script to run DBRepair
- Runs as the selected username
- Emails you the result
- Runs on the schedule you desire (Weekly after PMS scheduled tasks completed is optimal)
#!/bin/bash
# Go to the PlexMediaServer shared folder
cd /var/packages/PlexMediaServer/shares/PlexMediaServer
# Run an intelligent "Stop PMS - Automatic - Start PMS" and exit sequence
sudo ./dbrepair auto exit